roadmap/linked-list/Reverse Linked List

Reverse Linked List

EasyAmazonGoogleMetaMicrosoftApple
Solve on LeetCode ↗

Given the head of a singly linked list, reverse the list and return the reversed list's head.

Iteratively: maintain prev=null, curr=head. At each step, save curr.next, point curr.next to prev, move prev to curr, move curr to saved next. When curr is null, prev is the new head.

Iterative three-pointer

prev=None, curr=head. Loop: nextTemp=curr.next, curr.next=prev, prev=curr, curr=nextTemp. Return prev.

Time
O(n)
Space
O(1)

Single pass. Three pointers — constant space.

Python
def reverseList(self, head: ListNode) -> ListNode:
    prev, curr = None, head
    while curr:
        next_temp = curr.next
        curr.next = prev
        prev = curr
        curr = next_temp
    return prev
Empty list: return null
Single node: return as-is

What pattern do you think this problem uses?

Progress is saved on this device