我有一个节点类和 TestMain 类,用于创建和测试链接列表。我已经覆盖了 Node 类中的 toString 方法来打印 Node(值和下一个)。但它递归地打印列表。我只想打印我指定的节点。谁能告诉我
- 为什么我的 toString 递归打印整个列表?
- 需要更改什么以仅在 main() 中打印我想要的节点
public class Node {
private int value;
private Node next;
Node(int value){
this.value=value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString(){
return "value = " + this.value + ", next = " + getNext();
}
}
public class TestMain {
public static void main(String[] args) {
System.out.println("Begin TestMain \n");
Node head = new Node(10);
Node n1 = new Node(11);
Node n2 = new Node(12);
Node n3 = new Node(13);
head.setNext(n1);
n1.setNext(n2);
n2.setNext(n3);
System.out.println("Head : " + head);
System.out.println("n1 : " + n1);
System.out.println("n2 : " + n2);
System.out.println("n3 : " + n3);
System.out.println("\nEnd TestMain");
}
}
//>>>>>> output <<<<<<<<<
Begin TestMain
Head : value = 10, next = value = 11, next = value = 12, next = value = 13, next = null
n1 : value = 11, next = value = 12, next = value = 13, next = null
n2 : value = 12, next = value = 13, next = null
n3 : value = 13, next = null
End TestMain
//>>>>> Expected Output <<<<<<<<
Begin TestMain
Head : value = 10, next = addressOf-n1
n1 : value = 11, next = addressOf-n2
n2 : value = 12, next = addressOf-n3
n3 : value = 13, next = null
End TestMain