JavaScript链表push方法底层原理解惑:未直接操作head.next为何head的next属性自动更新?
head.next update automatically when calling push() in my LinkedList implementation? Hey there, let's unpack this confusion—it's actually a core concept about how JavaScript handles objects, so once you get it, everything will click!
Let's walk through your code step by step:
When you initialize the linked list
let myLinkedList = new LinkedList(7);Inside the
LinkedListconstructor, you create a newNodeClasswith value 7. Then you setthis.head = newNodeandthis.tail = this.head.Here's the key:
this.headandthis.taildon't store the node object itself—they store a reference to that same node object in memory. So right now, both variables point to the exact sameNodeClass { value: 7, next: null }instance.When you call
push(4)
First, you create a new node with value 4. Then you do:this.tail.next = newNode;Since
this.tailis still referencing the original node (value 7), modifyingthis.tail.nextis the same as modifying thenextproperty of that original node. And becausethis.headalso references that same original node, when you checkthis.head.next, it will show the new node with value 4—you're looking at the same object through a different reference.After that, you update
this.tail = newNode, so nowthis.tailpoints to the new node (value 4), whilethis.headstill points to the original node (value 7).What happens with more
pushcalls?
Each time you callpush, you're taking the currenttail(which is the last node in the list), setting itsnextproperty to the new node, then updatingtailto be the new node. Theheadalways stays pointed to the first node, and since each node'snextproperty links to the next one in the chain, followinghead.next.next...will traverse the entire list—even though you never directly modifyheadafter initialization.
To sum it up: JavaScript objects are passed by reference. When multiple variables reference the same object, changes to that object's properties are visible through all references. Your push method modifies the next property of the current tail node (which, initially, is the same node as the head), so the head's next property updates as a side effect of that change.
内容的提问来源于stack exchange,提问作者Poor programmer

