why object values change even though it has different references?

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:

so current = [1,3,4] and it doesn’t point to result anymore.

Importantly, the 1 in that list is the same element as the 1 in 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 result and current started at referencing the same object, and then as the last step of the first iteration, current was changed to reference current.next. Since current and result were at that point the same, current.next and result.next are also the same. So after changing current to current.next, that’s the same as setting it to result.next.

So on the second iteration, result.next and 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 l2 referenced.

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.

Leave a Comment

Your email address will not be published.

Scroll to Top