Middle of the Linked List

Return the middle node of a linked list in a single walk, with one pointer moving twice as fast as the other.

A singly linked list is a chain of nodes: each node holds a value and a link to the next node, and the last node links to null. Given head, the first node of such a list, return its middle node. When the list has an even number of nodes, there are two middle nodes; return the second one.

Example 1
Input: head = [1, 2, 3, 4, 5]
Output: [3, 4, 5]
Explanation: the middle node is 3. Returning it also returns the nodes after it, so the output reads from 3 to the end.
Example 2
Input: head = [1, 2, 3, 4, 5, 6]
Output: [4, 5, 6]
Explanation: 3 and 4 are both middle nodes, and the second one is 4.
Solution

The Idea

Finding the middle book on a shelf is easy, because you see all the books at once. A linked list does not give you that view. You hold only the first node, and from each node you can step only to the next one, so you cannot tell how long the list is without walking it.

In Example 1 the list is 1, 2, 3, 4, 5. Node 3 has two nodes on each side, so it is the middle. In Example 2 the list is 1 to 6, and no single node sits in the centre: 3 and 4 share it, and the problem picks 4. So how do we reach the middle when we do not know the length?

Imagine two people walking along the list from the first node. One takes one node per round, the other takes two. When the faster one runs out of list, the slower one has covered half the distance, so it stands on the middle. A variable that refers to a node is called a pointer, and here the two walkers are two pointers, named slow and fast. Look at the picture below.

The list 1 to 6, round by round. At the start slow and fast are both on node 1. After round 1 slow is on 2 and fast on 3. After round 2 slow is on 3 and fast on 5. After round 3 fast is null and slow is on 4, the middle.

In the row labelled start, both pointers are on node 1. After round 1, slow is on 2 and fast on 3. After round 2, they are on 3 and 5. In round 3, fast steps from 5 over 6 to null, past the end of the list. That ends the walk, and in the row labelled after round 3, slow is on node 4, the second middle.

With the five nodes of Example 1, the walk ends one step sooner. After round 2, fast is on node 5, the last node, so it has no two nodes left to move, and slow is on node 3. One walk is enough, and it never needs the length. This pair of pointers is known as the slow and fast pointer technique.

Solution Approach

Turning that idea into code means looking at the simple way of counting first, then settling when the fast pointer must stop and which middle that stop gives for an even length.

Counting first, then walking

Why not just count the nodes? That works: walk the whole list to count n nodes, then start again from head and take n / 2 steps. For 6 nodes, 6 / 2 = 3 steps lead from node 1 to node 4. But it walks the list twice, while the two pointers find the same node in one walk.

When the fast pointer stops

When can fast take another two steps? Each round it moves with fast = fast.next.next, so both fast and fast.next must be real nodes. That gives the loop test fast != null && fast.next != null. The check fast != null ends an even-length walk, where fast has fallen off the end, as in round 3 of the picture. The check fast.next != null ends an odd-length walk, where fast sits on the last node.

The order of the two checks matters. Java checks the right side of && only when the left side is true, so fast.next is never read while fast is null.

Which of the two middles

Why does the walk land on 4 and not on 3? Because fast is allowed to step off the end in the last round, which gives slow one more step. If the test were fast.next != null && fast.next.next != null instead, fast would stop on node 5, one round earlier, and slow would stay on 3, the first middle. Some problems want that one, so the loop test is the place to choose.

Java Solution

The method middleNode works in these steps:

  1. First, point two variables, slow and fast, at head.
  2. Then loop while fast != null && fast.next != null. Each round, slow moves one node with slow = slow.next, and fast moves two with fast = fast.next.next.
  3. When the loop ends, return slow, the middle node. The nodes after it stay linked to it, so printing from it shows the rest of the list.

Around the method, a small ListNode class holds one node, build makes a list from values, and show prints a list from a given node to the end. The main method runs both examples, a list of one node and a list of two nodes.

Java
public class MiddleOfLinkedList {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
    }

    public static ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;          // one step
            fast = fast.next.next;     // two steps
        }
        return slow;
    }

    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 node) {
        StringBuilder sb = new StringBuilder("[");
        for (; node != null; node = node.next) {
            sb.append(node.val).append(node.next != null ? ", " : "");
        }
        return sb.append("]").toString();
    }

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

Running it prints:

Output
[3, 4, 5]
[4, 5, 6]
[7]
[2]

The six-node list gives [4, 5, 6], starting at node 4, the second middle, just as in the picture. Above it, [3, 4, 5] starts at node 3, the single middle of five nodes.

Look at the last two lines. For the list [7], fast starts on the only node, whose next is null, so the loop never runs and that node is its own middle. For [1, 2], both nodes are middles. One round moves slow to 2 and fast to null, so the method returns node 2, the second one.

Complexity

The work is a single walk of the two pointers, which stops when fast reaches the end.

  • Time: O(n), for a list of n nodes: fast passes over each node at most once, two per round, so the loop runs about n / 2 rounds, each a few pointer moves.
  • Space: O(1). However long the list is, the method keeps only the two pointers. It neither counts the nodes nor copies them into an array.

Finding the middle is also the first step of Palindrome Linked List, which checks whether a list reads the same from both ends.