Result and current point to diffrent objects, still when current changes result does as well. How result keeps reference to current?
Look at this part of your question:
current = [1,3,4]and it doesn’t point to result anymore.
1 in that list is the same element as the
result = [0,1,3,4]. If you modify the
next field of that
1 node, you will modify any list that node is a member of. Including the list that
result is referencing.
Later when you write:
At this moment we have:
result = [0,1,1,2,4], current = [1,1,2,4], l2 = [3,4], l1 = [2,4]
Note that the list
result points to is not the same as the list
current points to. But after that first node, it is the same.
After the first iteration,
result.next references the same object that
current does. This is because
current started at referencing the same object, and then as the last step of the first iteration,
current was changed to reference
result were at that point the same,
result.next are also the same. So after changing
current.next, that’s the same as setting it to
So on the second iteration,
current are the same. This means that when you modify
current.next, that’s the same as modifying
result.next.next, which has the effect of replacing the contents of the
result list beyond the first two elements, with the new chain of elements that
Again: the key here is that each variable simply points to a single node. It’s fine to conceptualize that as pointing to a list of nodes, but only if you remember that if you modify the
next field of any node in that list, you are modifying the entire list, even if the variable is not referencing the variable that references the root of the list.
CLICK HERE to find out more related problems solutions.