Given the head of a singly linked list head, reverse the list, and return the new head.
Example:
reverseList(ListNode.of([1]))
# ListNode.of([1])reverseList(ListNode.of([1, 2]))
# ListNode.of([2, 1])reverseList(ListNode.of([1, 2, 3]))
# ListNode.of([3, 2, 1])To solve this problem, we need to "reverse" all the pointers in the list. To do this, we have to start at the head node, and reverse all the nodes one at a time:
In order to reverse a node, we have to keep track of the current node curr that we want to reverse. We also have to keep track the previous node prev, so that we can point the current node backwards to it.
It turns out that we also need to save a pointer to the next node in the list temp_next so that we still have access to it when we reverse the pointer.
Here's a visual of how you reverse a single node:
Here's the code for the above image:
temp_next = curr.next # save a pointer to curr.next before reversing it
curr.next = prev # reverse `curr.next`
# move `prev` and `curr` pointers up by 1
prev = curr
curr = temp_nextTo reverse the whole list, we repeat the above code until we've reversed the entire list.
We start with these prev and curr pointers:
And we finish with these pointers:
When we finish, we should return the head of the reversed list which is the prev pointer (from Image 1). Here's how you code this up:
def reverseList(head):
# starting pointers
prev = None
curr = head
while curr: # loop until curr is null
temp_next = curr.next
curr.next = prev
prev = curr
curr = temp_next
# return the head of the reversed list
return prev