Kor*_*gay 0 java recursion linked-list
码:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
测试类:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行这个main方法时,该方法似乎不会在3之后退出.输出为:1 2 3 3 3 3 3 3 3
任何人都可以看到问题出在哪里?
更改
while(this.next != null){
Run Code Online (Sandbox Code Playgroud)
至
if(this.next != null){
Run Code Online (Sandbox Code Playgroud)
如果您以迭代方式打印列表,则需要循环.在递归解决方案中,您没有.