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"
}