简体   繁体   English

如何理解while循环——链表

[英]how to understand while loop - linked list

So I am learning on my own, and ran across this code for reversing a linked list:所以我自己学习,并遇到了这段代码来反转链表:

function reverseLinkedList(linkedList) {
  let node = linkedList.head;
  let first = node;
  let next = null;
  let prev = null;

  while (next = node.next) {
    node.next = prev;
    prev = node;
    node = next;
  }

  linkedList.head = node;
  linkedList.head.next = prev;  
  linkedList.tail = first;

  return linkedList;
}

Now my question is, how in the...How does while(next = node.next) work if it is not a conditional statement.现在我的问题是,如果...不是条件语句,while(next = node.next) 是如何工作的。 My guess is that it turns into node.next becomes undefined when reaching the tail node and calling.next, and that in turn breaks the while loop.我的猜测是,当到达尾节点并调用.next 时,它变成了 node.next 变得未定义,这反过来又打破了 while 循环。 However, I am not positive this is the case.但是,我并不肯定这种情况。

IIRC it is semantically equal to: IIRC 它在语义上等于:

next = node.next
while (next) 
{
    // ...
}

Meaning, when next == null (or any falsy value), the loop's condition is false , therefore the loop terminates.这意味着,当next == null (或任何虚假值)时,循环的条件为false ,因此循环终止。

while (next = node.next) {
    node.next = prev;
    prev = node;
    node = next;
}

is same as

next = node.next
while (next != NULL) {
    node.next = prev;
    prev = node;
    node = next;
    next = node.next
}

In JavaScript (and many other languages with this sort of syntax) the result of an assignment statement is the value assigned.在 JavaScript(以及许多其他具有这种语法的语言)中,赋值语句的结果是赋值。 So, in this case, the while evaluates each node which is either a value or not.因此,在这种情况下,while 会评估每个节点,它要么是一个值,要么不是一个值。 This is so you can chain assignments like x = y = 5 , but also you can evaluate them as conditionals too.这样您就可以像x = y = 5这样的链接分配,而且您也可以将它们评估为条件。 See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment请参阅: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment

You're right.你是对的。 As you pointed out, the while loop stops executing the moment node.next becomes undefined .正如您所指出的, while循环在node.next变为undefined时停止执行。 It uses the right-hand side of next = node.next as conditional.它使用next = node.next的右侧作为条件。 In this case node.next .在这种情况下node.next

To illustrate my point, consider the following piece of code:为了说明我的观点,请考虑以下代码:

let i = 0
const values = [1, 2, undefined, 3]
while (x = values[i]) {
  console.log(x);
  i += 1;
}

This will print:这将打印:

1
2

Stopping the execution the moment it reaches undefined (Any Falsy value would produce the same effect)在达到undefined的那一刻停止执行(任何Falsy值都会产生相同的效果)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM