0
我初始化LinkedNode“node”成为关键字“this”,然后将新节点“last”追加到创建的节点“node”的末尾。但是请注意,在while循环中,我将“节点”更改为“node.next”。为什么当我运行该程序时打印出正确的结果?也许我不太明白“这个”。我如何在方法append(int n)中更改“this”?
public class LinkedNode {
protected LinkedNode next;
protected int data;
LinkedNode(int d) {
data = d;
}
public void append(int n) {
LinkedNode node = this;
LinkedNode last = new LinkedNode(n);
while (node.next != null) {
node = node.next;
}
node.next = last;
}
public static void main(String[] args) {
LinkedNode Node = new LinkedNode(2);
Node.append(3);
Node.append(4);
Node.append(5);
for (int i = 0; i < 4; i++) {
System.out.println("Data: "+Node.data);
Node = Node.next;
}
}
//Output is correctly "2 3 4 5"
}