I am trying to solve some problems on Leetcode.
I completed the Reverse Linked List problem, which basically requires you to reverse a singly linked list. My solution is this:
def reverseList(self, head):
curr = head
prev = None
if head != None:
while (curr.next):
temp = curr.next
curr.next = prev
prev = curr
curr = temp
curr.next = prev
return curr
I used a temp value to keep track of the original NEXT node after the current node, before the value of the NEXT node is changed in the following line.
However, when I compare my solution to other solutions, it seems that there was no need for a temporary value at all. Below is a sample solution:
def reverseList(self, head):
curr, prev = head, None
while curr:
curr.next = prev
prev = curr
curr = curr.next
return prev
No temporary value was used, which I am trying to figure out why. The below image is my mental visualisation of what happens in the solution:
Why is it possible for the code to be able to still assign curr = curr.next (line 4 of solution) after curr.next was mutated? (line 6 of solution)
