1

I am writing a function to remove a sorted linklist's duplicated nodes which has the same value.

Ex: const linkList = 1 -> 1 -> 3 -> 4 -> 4 -> 4 -> 5 -> 6;

Here is my code:

function removeDuplicatesFromLinkedList(linkedList) {
  let currentNode = linkedList;
    while (currentNode !== null) {
        let nextNode = currentNode.next;
        // use `while` here rather than `if` is in case there are too many
        // consecutive duplicated values
        while (nextNode !== null && nextNode.value === currentNode.value) {
            nextNode = nextNode.next;
        }
        currentNode.next = nextNode;
        currentNode = nextNode;
    }
    
  return linkedList;
}

For the second while loop, if I move the condition nextNode !== null to the second place, then most of the test cases will be failed. Any ideas why? I thought the while block of code only will be executed when both conditions are correct.

qmkiwi
  • 135
  • 1
  • 5
  • If `currentNode` has no property called nextNode, then `currentNode.nextNode === undefined`, not null, so your condition will fail. – James Jul 14 '21 at 19:32
  • You are correct, the order of the && operator does not matter (in fact, it will short circuit and return false on the first false condition). You can verify in the node console: `1 != 1 && console.log("A") == undefined` will not log, but `console.log("A") == undefined && 1 != 1` will log. – swagrov Jul 14 '21 at 19:32

0 Answers0