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.