0

Suppose we have a single linked list 1->2->3->4->5 and 1 is the head

ListNode newHead = new ListNode(0);
ListNode p = newHead;  
ListNode runner = newHead; 
newHead.next = head; // Line 1 p and runner next is also head
while(n>0){
    runner = runner.next; // Line 2 why newHead and p does not move along with runner just as above because they are equal object (I assume)
    n--;
}

Why don't p, newHead and runner all change at the same time? In Line 1 they do, but in Line 2 they don't, why?

luk2302
  • 55,258
  • 23
  • 97
  • 137
sevenxuguang
  • 177
  • 9
  • Where do you define `head` ? Line 1 seems to be used to make the while loop work for the head of the list too. Could you also explain the expected behavior of the code? – toasted_flakes Dec 26 '15 at 16:59

1 Answers1

1

Assume newHead is at memory location A.
Since you assign newHead to p, p now points to memory location A as well.
Same logic for runner, pointing to A.

Now you set some property of the newHead, which "changes" the property on all three newHead, p and runner since all point to the same object in the same memory location A.

If you now write runner = runner.next you assign a new value to runner.
Now runner points to memory location B.

But that simply does not matter for p and newHead since they only pointed to the same location as runner but had no other relation than that. They only pointed to the same location / the same object. If you change the object all three know of that change. But if you change where one of the three points to, that does not matter for the other two.

Java non-primitive variables are simply pointers / references to memory addresses where the actual object lies. Without you as the developer having to deal with the problems that might arise from pointers (or having access to the features they provide).

luk2302
  • 55,258
  • 23
  • 97
  • 137