Data Structures

Reverse Linked List

Linked List

Given the head of a singly linked list head, reverse the list, and return the new head.

Example:

Reverse Linked List - image
First Few Test Cases:
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:

Reverse Linked List - image

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:

Reverse Linked List - image

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_next

To reverse the whole list, we repeat the above code until we've reversed the entire list.

We start with these prev\small \tt prev and curr\small \tt curr pointers:

Reverse Linked List - image

And we finish with these pointers:

Reverse Linked List - image

When we finish, we should return the head of the reversed list which is the prev\small \tt 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
Mark as Completed:
Submits:
reverseList
Imports:
ListNode
Test your code to get an output here!
reverseList(
)
Test your code to get an output here!