You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript链表push方法底层原理解惑:未直接操作head.next为何head的next属性自动更新?

Why does 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:

  1. When you initialize the linked list

    let myLinkedList = new LinkedList(7);
    

    Inside the LinkedList constructor, you create a new NodeClass with value 7. Then you set this.head = newNode and this.tail = this.head.

    Here's the key: this.head and this.tail don'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 same NodeClass { value: 7, next: null } instance.

  2. When you call push(4)
    First, you create a new node with value 4. Then you do:

    this.tail.next = newNode;
    

    Since this.tail is still referencing the original node (value 7), modifying this.tail.next is the same as modifying the next property of that original node. And because this.head also references that same original node, when you check this.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 now this.tail points to the new node (value 4), while this.head still points to the original node (value 7).

  3. What happens with more push calls?
    Each time you call push, you're taking the current tail (which is the last node in the list), setting its next property to the new node, then updating tail to be the new node. The head always stays pointed to the first node, and since each node's next property links to the next one in the chain, following head.next.next... will traverse the entire list—even though you never directly modify head after 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:02:45