educative.io

Educative

Why interchanging these two lines breaks the program?

What is happening after interchaning the lines currentHead = currentHead.next; and temp.next = reversedList;

This works

while (currentHead) {
    let temp = currentHead;
    currentHead = currentHead.next;

    temp.next = reversedList;
    reversedList = temp;
}

this doesn’t

while (currentHead) {
    let temp = currentHead;

    temp.next = reversedList;
    currentHead = currentHead.next;

    reversedList = temp;
}

In the first code snippet, the currentHead pointer moves forward one step to the next node. The temp pointer then changes the next pointer of the previous currentHead node to reversedList.

In the second snippet, temp is first set to point towards the same node as currentHead. The next pointer of this node is then set to point towards reversedList. The currentHead pointer then moves forward towards the next node, which has now been changed to reversedList rather than the node it was initially pointing to.