【问题标题】:While loop in linked list链表中的while循环
【发布时间】:2015-12-08 20:39:36
【问题描述】:

我不明白为什么这个循环实际上是遍历链表。我知道这是一个愚蠢的问题。没有任何增量;看起来它一次又一次地遍历同一个元素。

current = head;
while(current.next) {current = current.next;}
current.next = node;

【问题讨论】:

  • 它的工作原理和它说的完全一样……你知道什么是链表吗?
  • 链表中的每个节点都有一个数据元素和一个指向链表中下一项的“链接”(下一个)。如果“下一个”链接为空(常用),则您位于列表的末尾。所以,当前节点=头;表示从头开始,然后当有节点移动到时 (current.next [test ! false-y ]) current = current.next;前进到下一个节点。在循环之后,你就到了最后,所以追加新节点 current.next = node; node.next 应该是 false-y,例如 0 或 null;

标签: javascript loops


【解决方案1】:

我假设您对 LinkedList 在概念上的工作原理有一个基本的了解。

实际的节点类在这里不可见,但我们假设它看起来像这样

function Node (type) { this.next // points to next node in list // some more fields containing data }

现在,一行一行:

current = head

这会将列表的最前面的元素分配给变量current

while(current.next)

这表示只要currentnext 字段指向有效节点,就继续while 循环。

current = current.next

我认为这是造成最混乱的那一行。一开始currenthead 节点(最前面)。分配current = current.nextcurrent 中的next 字段分配为等于current 本身。这样,在while循环的每一次迭代中,current都会成为它的下一个节点并遍历列表(只要currentnext字段中包含一个有效节点。

关键思想是current = current.next 不断分配下一个节点,因此列表正在传播。

【讨论】:

    【解决方案2】:

    之所以有效,是因为赋值运算符将 current 更改为之前的 next 属性:

                 ┌──────────┐             ┌──────────┐
                 │          │   next      │          │   next
                 │      *───┼──────────> │      *───┼─────────>
                 │          │             │          │
                 └──────────┘             └──────────┘
                      ↑
    current ─────────┘
    

    在执行current = current->next 语句时,current 将引用在赋值之前引用的current->next

                 ┌──────────┐             ┌──────────┐
                 │          │   next      │          │   next
                 │      *───┼──────────> │      *───┼─────────>
                 │          │   ┌──────> │          │
                 └──────────┘   │         └──────────┘
                                 │
    current ───────────────────┘
    

    在下一次迭代中,current 因此不再与上一次迭代相同,其next 属性指向列表中的下一个对象。将该next 属性分配给current 后,它看起来像这样:

                 ┌──────────┐             ┌──────────┐
                 │          │   next      │          │   next
                 │      *───┼──────────> │      *───┼─────────>
                 │          │             │          │    ┌────>
                 └──────────┘             └──────────┘    │
                                                             │
    current ────────────────────────────────────────────┘
    

    ...等等

    【讨论】:

      【解决方案3】:

      我把它读成:

      只要current 具有.next 值,就将电流设置为该值。

      current 不再具有.next 值时——从给定的node 创建并设置新的.next 值。

      【讨论】:

        猜你喜欢
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        • 2014-11-02
        • 2023-03-30
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多