Code:
public class NodeType {
public int value;
public NodeType next;
public NodeType(){
value = 0;
next = null;
}
public void printFollowingNodesInOrder(){
System.out.println(this.value);
while(this.next != null){
this.next.printFollowingNodesInOrder();
}
}
}
Test class:
public class TestClass {
public static void main(String[] args){
NodeType nodeOne = new NodeType();
NodeType nodeTwo = new NodeType();
NodeType nodeThree = new NodeType();
nodeOne.value = 1;
nodeTwo.value = 2;
nodeThree.value = 3;
nodeOne.next = nodeTwo;
nodeTwo.next = nodeThree;
nodeOne.printFollowingNodesInOrder();
}
}
When I run this main method, the method does not seem to exit after 3.
The output is:
1
2
3
3
3
3
3
3
3
Can anyone see where the problem is?
is looping forever once it starts calling
printFollowingNodesInOrderon the final node, because the second to last node (the one where the function is being called) has anextthat will never go away. You don’t need to do it in a loop when you’re using recursion to access the next node. Take the loop out and it will work, but be sure to check for null before calling the function.