Reverse Linked List, visualized step by step

Easy One of the Blind 75 interview problems (LeetCode 206). Technique: linked list. Solution in Python, explained at every step.

The problem

You get the head of a singly linked list: each node holds a value and a link to the next node, and the last node links to nothing. Reverse the list and return its new head.

Example: 7 → 3 → 9 → 4 becomes 4 → 9 → 3 → 7, and the function returns the node holding 4.

Input: the list 7, 3, 9, 4, each node linking to the next and the last to nothing. Answer: 4, 9, 3, 7 linked the same way.
The answer is the same four nodes; only their links point the other way, and the head is now the node that was last.

Try it yourself first: LeetCode 206 ↗. Then step through the solution below.

Brute force

Copy the values into an array, then walk the list again and write them back in reverse order. That is O(n) time but O(n) extra space for the array, and it changes values rather than links. Building a second, reversed list node by node has the same O(n) space cost.

The key insight

A node only knows the node after it, so the list can be reversed by turning each link around: a node should link to the node before it instead. The catch is that turning a link loses the way forward.

So walk with three variables: prev, the part already reversed; curr, the node being turned; and nxt, saved before the turn so the walk can go on. Each node is turned once.

Step by step

The player runs the code on the example. Press → for each step: the lines it runs light up in the code.

On a phone, Full screen keeps the picture and the code on one screen.

Reverse Linked List, step by step

Python

class Node:    def __init__(self, val, next=None):        self.val, self.next = val, next def reverse(head):    prev = None    curr = head    while curr:        nxt = curr.next        curr.next = prev        prev = curr        curr = nxt    return prev
All steps as text
  1. The list is 7 → 3 → 9 → 4. Reversed, it should read 4 → 9 → 3 → 7.
  2. The variable prev refers to no node yet (∅), and curr to the head, 7.
  3. Save the node after 7, which is 3, in nxt: once 7's link turns, nxt is the only way to reach 3.
  4. Turn 7's link back to prev, which is no node (∅): 7 will be the end of the reversed list.
  5. Move prev to 7 and curr to 3.
  6. Save the node after 3, which is 9, in nxt.
  7. Turn 3's link back to prev, 7.
  8. Move prev to 3 and curr to 9.
  9. Save the node after 9, which is 4, in nxt.
  10. Turn 9's link back to prev, 3.
  11. Move prev to 9 and curr to 4.
  12. The node 4 has no node after it, so nxt refers to no node (∅).
  13. Turn 4's link back to prev, 9.
  14. Move prev to 4, and curr past the end to no node: the loop ends.
  15. Return prev: 4, the head of the reversed list 4 → 9 → 3 → 7.
  16. Each link was turned once: O(n) time, and three variables were enough: O(1) space.
Reverse Linked List, step by step. Last step: Each link was turned once: O(n) time, and three variables were enough: O(1) space.

Note

In Python the loop body is often one line: curr.next, prev, curr = prev, curr, curr.next. The right side is worked out first, but the names on the left are assigned one by one, from left to right. Put curr first, and the link is then turned on the next node instead of this one: the list breaks.

Complexity

ApproachTimeSpace
Brute force: copy the values into an arrayO(n)O(n)
RecursionO(n)O(n)
Turn the links in one pass this pageO(n)O(1)
  • Time: O(n). The loop visits each node once and does a fixed amount of work there.
  • Space: O(1). Three variables, whatever the length of the list; the nodes are reused, not copied.

Edge cases

  • An empty list: curr starts as None, the loop never runs, and the function returns None.
  • A single node: its link is turned to None, where it already pointed, and the same node comes back as the head.
  • Two nodes, like 1 → 2: two turns give 2 → 1.

Try it: put Reverse Linked List together step by step

The blocks below are steps of Reverse Linked List in words, and one of them does not belong. Put the right ones in order and check: your algorithm runs on the example, 7 → 3 → 9 → 4, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.

Put Reverse Linked List together

Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. One of them doesn't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.

Your algorithm

Blocks

Interview follow-up

Can you do it recursively? Yes: reverse everything after the head first, then make the head's next node link back to the head and set the head's link to None. Leave out that last part, and the first two nodes link to each other: a loop, not a list. It is also O(n) time, but each node waits on the call stack, so it takes O(n) space, and a very long list can exceed the recursion limit.

The data structure behind it