Reputation: 163
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
ListNode newNode = null;
ListNode nxt = head.next;
head.next = newNode;
newNode = head;
head = nxt;
Here is what I visualize when I see this:
Say I have a structure
where ------->
means pointing to (as in memory)
head -------> 1->2->3->4->5->6
Then this means
ListNode nxt = head.next -------> 2->3->4->5->6
Then when you do:
head.next = newNode
head -------> 1->NULL
Then shouldn't nxt
become?
nxt -------> NULL
Since you changed what nxt
is pointing to?
Upvotes: 0
Views: 87
Reputation: 1498
Imagine:
You have one red arrow that points to a whole bunch of green arrows.
Now get two friends, blindfold them and get them ear pieces (so that nobody can hear what you tell the other one). We're gonna call them "Tim the guy with a head" and "Bob the next guy".
Take Tim's arm and point it to the red arrow.
Now remove Bob's blindfold. Tell him to look at what Tim is pointing to and point to whatever that points to. Since Tim is pointing to the red arrow and the red arrow points to the green arrows, Bob will now point to the green arrows. Now reapply Bob's blindfold.
Next, it's time to change what the red arrow is pointing to, so turn it by 90°, so now it points to nothing.
And now aks yourself: What is Bob pointing to?
The answer should obviously be that Bob is still pointing to the green arrows.
If you arrived at the same conclusion: Make sure you understand that this is exactly what happens in the case you described in your question.
If you thought Bob would be pointing at nothing now, I encourage you to just try it out in real life ;)
Upvotes: 0
Reputation: 15674
But you didn't change where nxt
is pointing to.
ListNode nxt = head.next
This makes nxt
point to the same thing as head.next
, which in this case is the 2.
head.next = newNode
This changes head.next
. It changes nothing else; nxt
remains as it was, and continues to point to the 2.
Upvotes: 2