简体   繁体   中英

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. 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. However, I am not positive this is the case.

IIRC it is semantically equal to:

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

Meaning, when next == null (or any falsy value), the loop's condition is false , therefore the loop terminates.

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. So, in this case, the while evaluates each node which is either a value or not. This is so you can chain assignments like x = y = 5 , but also you can evaluate them as conditionals too. See: 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 . It uses the right-hand side of next = node.next as conditional. In this case 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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