The issue: Swapping Elements in a Linked List
In this article, there is a strange change happening that I can not follow… it all WORKS in the end but I need help understanding WHY
It is difficult to explain but I will try.
We are trying to swap 2 nodes in a linked list, node1, and node2. We look for data1 and data2 in the list and then switch the position of these two nodes, obviously by changing their pointers.
Let’s say that I have a
testList from 1 - 10.
I want to swap 6 and 5 using the
swapNodes(testList, 6, 5) function.
I follow the changes through the function with
console.log so I can confirm my predictions.
The problem is that the
node2.next.data value is changed and I can’t figure out why.
Follow what happens first:
node2Prev = 4- makes sense
node2 = 5- correct
node2.next.data = 6- also correct
I can follow this as the 4, 5, 6 are the logical values for node2.
node1Prev.nextis assigned to
node2(which is 5)
node2.next.datais now 5 - WHY!?!
This is the problem, why does
node2.next.data become 5? It was 6 a just a few lines ago and nowhere in between was it changed by the code…
Can anyone explain to me why
node.next.data is changed to 5 seemingly at random? When, in my opinion, it should be 6.
Thanks so much, appreciate your time.
The Code - GitHub