← Linked Lists

Drill #11 — Reverse a linked list

Easy prev/cur/nxt Linked Lists

In plain English: Make a linked list point backwards so the last node becomes the first.

Rewire each node to point backward by keeping three pointers — previous, current, and the saved next.

Prompt

Reverse a singly linked list in-place.

Try to write it from scratch before scrolling down.

Solution

def reverse(head):
    prev, cur = None, head
    while cur:
        nxt = cur.next  # save next before rewiring
        cur.next = prev
        prev = cur
        cur = nxt
    return prev

# Test: 1->2->3->4 => 4->3->2->1
O(n) time · O(1) space

Related Micro Drills

← Drill #10 Drill #12 →