I have this question:
Write a recursive java function that counts the number of nodes in a circularly linked list.
Here is the method/function:
public int countNodes(Node node){
if (node == null) {
return 0;
}
else{
return 1+countNodes(node.next);
}
}
I get an error in the line return 1+countNodes(node.next); which says that: next cannot be resolved to a value or field in java
What am I supposed to do to fix this error?
The Node class should be like this:
public class Node {
private Node next;
public Node getNext(){
return next;
}
//setter and other stuff
}
and you have to call node.getNext()
return 1+countNodes(node.getNext());
Don't forget that Java is a object oriented language.