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;
}