I saw this problem in Leet and wanted to try it. one of the solutions proposed was the one below, however, I am scratching my head a little bit. I do understand what's going on but I don't understand some behaviors.
var reverseList = function(head){
var tmp = null;
var newHead = null;
while(head !== null){
tmp = head;
head = head.next;
tmp.next = newHead;
newHead = tmp;
}
return newHead;
}
For the input of [5,4,3,2,1]
we get this in each iteration
[1,2,3,4,5]
[2,3,4,5]
null
[1]
[2,3,4,5]
[3,4,5]
[1]
[2,1]
[3,4,5]
[4,5]
[2,1]
[3,2,1]
[4,5]
[5]
[3,2,1]
[4,3,2,1]
[5]
null
[4,3,2,1]
[5,4,3,2,1]
here what's I am confused about
why is
tmp = head; //tmp = [1,2,3,4,5]
but whennewHead = tmp // newHead = [1]
and not [1,2,3,4,5]head = head.next;
doesn't seem to affect the two lines after it, but if we movehead = head.next;
to the last position, the code does not work
CodePudding user response:
why is
tmp = head; //tmp = [1,2,3,4,5]
but whennewHead = tmp // newHead = [1]
and not [1,2,3,4,5]
That is because between those two assignments, tmp.next
has been reassigned. In the first iteration, tmp.next
will be assigned null
, so that effectively cuts the list short to just the node tmp
itself.
head = head.next;
doesn't seem to affect the two lines after it, but if we movehead = head.next;
to the last position, the code does not work
That's because it has to happen before tmp.next
is assigned. If head = head.next
has not happened before tmp.next = newHead
is done, then tmp
and head
will still reference the same node, and thus tmp.next = newHead
will mutate that same node. Hence, after that has happened head.next
is no longer what it was before that assignment. This explains why head = head.next
would not have the same effect anymore (and not the correct effect).