0

This is simple question from the LeetCode : Reverse LinkedList I have two similar code and I can't figure it out what is difference between two but it outputs different result.

First while loop results correct answer but second one has wrong answer. Instead of temp = current. next, I just store current to temp and at the last line of the while loop, I correctly switch current to temp.next. I think they should result the same answer but when Input {1,2,3,4,5} then second solution got wrong answer {1}.

ListNode reverse = null;
ListNode current = head;

while(current != null){
  ListNode temp = current.next;
  current.next = reverse;
  reverse = current;
  current = temp;
}

Here is the second while loop.

while(current != null){
  ListNode temp = current;
  current.next = reverse;
  reverse = current;
  current = temp.next;
}

2 Answers 2

1
while(current != null){
    // This line temp is keeping the reference  of current variable
    ListNode temp = current;
    // now temp and current both pointing to same value

    // This line will make the next of current variable pointing to reverse reference
    // as current and temp were same so next of temp is also pointing to the reverse
    current.next = reverse;

    // now the reverse will be changed and point to the current reference
    reverse = current;
    // so up to here reverse, temp, current all pointing to the same location
    // as all are pointing same so temp.next,curr.next and reverse.next
    // will store the previous reference 

    // current will point back to the reverse value
    // no increment is done in the whole loop
    current = temp.next;
}
Sign up to request clarification or add additional context in comments.

Comments

0

In the second snippet, it may seem that current = temp.next sets current to its nextvalue from the top of the loop/the start or the current iteration - after all, nobody assigned something to temp.next.
But after temp = current, both are names for the same thing, and current.next = reverse overwrites something that will be needed and hasn't been saved.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.