[英]Java: Understanding the Singly Linked List implementation
考慮我正在嘗試添加 10、20 和 30。當我添加第一個節點 10 時,HEAD 將為空。 此時,HEAD 和 TAIL 將指向同一個節點,即 10。現在當添加第二個節點 20 時,我們正在更新 TAIL 的 next 指向節點 20。由於 HEAD 和 TAIL 共享相同的引用,因此 HEAD 也會更新. 到這里都很酷。 在此之后,我們正在更新尾部引用。 現在 HEAD 和 TAIL 不會共享公共引用,對嗎? 但是當我們添加第三個節點時 HEAD 是如何更新的? 我很困惑理解它......
public class LinkedList {
private class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
}
private Node head;
private Node tail;
public void add(int data) {
var node = new Node(data);
if (head == null) {
head = tail = node;
return;
}
tail.next = node;
tail = node; // At this point, TAIL and HEAD are no longer connected, right? Still how HEAD gets updated when we are updating only TAIL?
}
}
tail = node;
// 此時,TAIL 和 HEAD 不再連接了,對吧?
tail 是您添加的最后一個元素,執行tail = node;
是正常的tail = node;
改變舊尾巴,在這種情況下,頭部將與新尾巴連接。
//當我們只更新 TAIL 時,HEAD 是如何更新的? 在頭的第一次分配之后,在我們在鏈表中進行的所有添加過程中它仍然相同
當您執行tail = node
, tail
引用將更新為node
引用的位置。 head
參考仍然與您第一次設置的相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.