Reverse Linked List

easyLinked List29 stepsJava · Python · C++

Reverse a singly linked list in place. Walk the list with three pointers: save next, point curr.next back at prev, then step both forward. When curr falls off the end, prev is the new head.

▶ Watch the animated trace

Traced input: head = [1, 2, 3, 4, 5] → [5, 4, 3, 2, 1]. Original problem: neetcode.io/problems/reverse-a-linked-list

Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)

Each node's pointer is flipped once.

Key idea

Common mistakes

Solution

Java
ListNode reverseList(ListNode head) {
    ListNode prev = null, curr = head;
    while (curr != null) {
        ListNode next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}
Python
def reverseList(head: Optional[ListNode]) -> Optional[ListNode]:
    prev, curr = None, head
    while curr:
        nxt = curr.next
        curr.next = prev
        prev = curr
        curr = nxt
    return prev
C++
ListNode* reverseList(ListNode* head) {
    ListNode *prev = nullptr, *curr = head;
    while (curr) {
        ListNode* next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Empty list
The loop never runs; return null.
head = [][]
Single node
One flip to null.
head = [7][7]
Two nodes
The smallest case where links actually change direction.
head = [1, 2][2, 1]
← Largest Rectangle in HistogramMerge Two Sorted Lists →