0:00 / 0:00

Turn every arrow of a linked list around in place. Keep three pointers: save next, flip current back to previous, step forward.

▼

The problem

LeetCode 206 (Easy). Given the head of a singly linked list, reverse the list and return the new head.

Example: 1 -> 2 -> 3 -> 4 -> 5 -> null becomes 5 -> 4 -> 3 -> 2 -> 1 -> null; the function returns node 5.

TRY IT ON LEETCODE ▶

The solution

def reverse_list(head):
    prev, curr = None, head
    while curr:
        nxt = curr.next    # save
        curr.next = prev   # flip
        prev = curr        # step
        curr = nxt
    return prev

Transcript

Reverse Linked List. You're given the head of a singly linked list: a chain of nodes, where each one points only to the next. Reverse it, so every arrow points the other way, and return the new head.

Take one, two, three, four, five. One is the head, each node points to the next, and five points to null, the end. Reversed, it reads five, four, three, two, one. Now five is the head, and one points to null.

The easy way: walk the list and copy every value into an array. Then walk it again, writing the values back in reverse order. It works, but the array costs extra space, one slot for every node. We can do better, with no copy at all.

Turn the arrows around in place. But careful: if you flip a node's arrow before anything else, you lose the only path to the rest of the list. So keep three pointers. Previous, the part already reversed. Current, the node you're turning. And next, saved first, so the rest stays reachable. Save, flip, step.

Let's run it. Previous starts at null, current at one. Save two as next, then flip one to point at null. Step: previous moves to one, current to two. Save three, flip two back to one, and step again. Three, four and five each turn the same way. Now current is null, so we stop, and previous, node five, is the new head.

In code: previous is null, current is the head. While current isn't null, save its next, point its arrow at previous, then move previous to current, and current to next. When the loop ends, return previous.

Each node is visited once, so the time is O of n, and the three pointers are O of one extra space. There's also a recursive version: reverse the rest of the list, then hook the current node onto its end. It's neat, but each call waits on the stack, so it uses O of n space.

Save, flip, step. That's Reverse Linked List.