Reverse a Linked List

Turn every link of a singly linked list around, so the last node becomes the new head.

Given the head (first node) of a singly linked list, reverse the list so that its nodes come in the opposite order, and return the head of the reversed list.

Example 1
Input: head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Example 2
Input: head = [1, 2]
Output: [2, 1]
Example 3
Input: head = []
Output: []
Solution

The Idea

Think of a treasure hunt where each clue only tells you where the next clue is hidden. A singly linked list works the same way. Each piece is called a node, and it holds a value and a link, named next, to the node after it. The last node's next is null, meaning nothing follows. The list is handed over by its first node, the head.

Look at Example 1. The head holds 1, its next leads to 2, and so on up to 5, whose next is null. Reversed, 5 must come first and 1 last. The order of a linked list is nothing but its links. So can we leave every node where it is and only turn each link around, so that 2 points to 1 instead of 1 pointing to 2?

Turning a link has a catch. A node's next is all that still leads to the rest of the list. Once 1 points backward, nothing leads forward to 2 any more, unless we noted where 2 was first. So the reversal walks along the list with three variables that each hold one node: prev, curr and next. Look at the picture below.

Reversing the list 1, 2, 3, 4, 5. At the start every arrow points right. After turning 1 and 2, null is left of 1, 2 points to 1, prev is on 2, curr is on 3 and next is on 4. When finished, every arrow points left and prev is on 5, the new head.

The row labelled "start" is Example 1 as given. In the row labelled "after turning 1 and 2", 1 points to null and 2 points to 1. That is the turned part, and prev holds its last turned node, 2. curr holds 3, the next node to turn, and its orange arrow still points to 4.

Before that arrow is turned, next saves 4, so the rest of the list stays in reach. Then 3 is pointed at 2, prev moves onto 3 and curr onto 4. Every node is turned the same way. In the row labelled "finished", every arrow points left, curr has walked off the end to null, and prev holds 5, the new head.

So reversing a list is a single walk from the head to the end: prev one node behind, curr on the node being turned, and next one node ahead.

Solution Approach

Turning that idea into code means settling three things: where the three variables start, the order of the moves for each node, and when to stop. A recursive version, shown last, is an optional alternative.

Where the variables start

Why not copy the values into an array and write them back in reverse? That works, but it needs an extra array as long as the list and two passes over it. Turning the links needs only the three variables.

Before anything is turned, the turned part is empty, so prev starts as null. curr starts on the head. This also takes care of the end of the reversed list: the old head is turned first, toward prev, so its next becomes null.

The order of the moves

What happens to each node, and in which order? Four assignments: save curr.next in next, point curr.next at prev, move prev to curr, then move curr to next. The saving must come first. If the turn came first, curr.next would already hold prev, and the node that followed curr could no longer be found.

When to stop

When is every node turned? When curr has moved past the old last node and holds null. At that moment prev holds the old last node, which is the new head. An empty list fits the same rule: curr starts as null, nothing is turned, and prev, still null, is the empty answer.

A recursive version (optional)

Can the reversal be written without a loop? A method that calls itself on a smaller part of the input is called recursive. Here, reverseRecursive(head) first reverses everything after head, by calling itself on head.next. A list with no node or one node is already reversed, and is returned as it is.

When the call for [1, 2, 3], where head is 1, gets back the reversed rest, 3 then 2, node 1 still points to 2, which is now the end. So head.next.next = head hangs 1 after 2, and head.next = null makes 1 the new end. Without head.next = null, 1 and 2 keep pointing at each other. Following the links then gives 3 -> 2 -> 1 -> 2 -> 1 -> ... without end.

The recursive version is short, but every call waits for the call after it to finish, so a list of n nodes keeps n calls waiting at once. Java keeps them on the call stack, an area of memory with a fixed size, and a long list can fill it.

Java Solution

The method reverseList works in these steps:

  1. First, create prev as null, for the empty turned part, and curr as head, the first node to turn.
  2. Loop while curr is not null. Inside the loop, save curr.next in a new variable, next.
  3. Point curr.next at prev, which turns the link of this node.
  4. Move prev to curr and curr to next, one node further along.
  5. When the loop ends, return prev, the old last node.

The class also holds reverseRecursive from the optional part, a small ListNode class for the nodes, and two helpers: build makes a list from numbers, and show prints a list as [5, 4, 3, 2, 1].

The main method reverses the three examples and a one-node list with the loop, reverses Example 1 with the recursive version, and then gives both versions a list of 100,000 nodes.

Java
public class ReverseLinkedList {

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
        }
    }

    public static ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next; // remember the rest before cutting the link
            curr.next = prev;          // point backwards
            prev = curr;
            curr = next;
        }
        return prev;                   // the old tail is the new head
    }

    public static ListNode reverseRecursive(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseRecursive(head.next); // reverse everything after head
        head.next.next = head;         // the node after head now points back to it
        head.next = null;              // the old head becomes the end
        return newHead;
    }

    static ListNode build(int... values) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        for (int v : values) {
            tail.next = new ListNode(v);
            tail = tail.next;
        }
        return dummy.next;
    }

    static String show(ListNode head) {
        StringBuilder sb = new StringBuilder("[");
        for (ListNode n = head; n != null; n = n.next) {
            sb.append(n.val);
            if (n.next != null) {
                sb.append(", ");
            }
        }
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        System.out.println(show(reverseList(build(1, 2, 3, 4, 5))));
        System.out.println(show(reverseList(build(1, 2))));
        System.out.println(show(reverseList(build())));
        System.out.println(show(reverseList(build(7))));
        System.out.println(show(reverseRecursive(build(1, 2, 3, 4, 5))));

        int[] big = new int[100000];
        for (int i = 0; i < big.length; i++) {
            big[i] = i + 1;
        }
        System.out.println("loop, 100000 nodes: head is " + reverseList(build(big)).val);
        try {
            System.out.println("recursion, 100000 nodes: head is "
                + reverseRecursive(build(big)).val);
        } catch (StackOverflowError e) {
            System.out.println("recursion, 100000 nodes: StackOverflowError");
        }
    }
}

Running it prints:

Output
[5, 4, 3, 2, 1]
[2, 1]
[]
[7]
[5, 4, 3, 2, 1]
loop, 100000 nodes: head is 100000
recursion, 100000 nodes: StackOverflowError

Look at the third line, [], from Example 3. curr starts as null, so the loop never runs and the method returns prev, still null. Just below it, [7] is a single node coming back as it went in, after one turn that set its next to null.

The fifth line, [5, 4, 3, 2, 1] again, comes from reverseRecursive, so on Example 1 both versions agree. The last two lines show where they differ. The loop reverses all 100,000 nodes, and the new head holds 100000. The recursion would need 100,000 waiting calls, and with Java's default stack size it stops with StackOverflowError.

Complexity

Both versions turn each node's link once; they differ in the memory they need while doing it.

  • Time: O(n) for both. The loop runs once for each of the n nodes, with four assignments per round, and the recursion makes one call per node.
  • Space: O(1) for the loop, O(n) for the recursion. The loop only keeps prev, curr and next, and reuses the existing nodes. The recursion keeps one waiting call per node on the call stack, which is why the 100,000-node list overflowed it.

The same loop, applied to only a part of the list, solves Reverse Linked List II.