Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

The way your code stands, you are trying to access a non-existent field called "next" in Node. Either add that field (if Node is a class you created), or did you mean to call a method called next? If so, do node.next()

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top