Sort List

Sort a linked list by merging ever longer sorted runs of nodes, without recursion or an extra array.

Given the head of a linked list, sort the list in ascending order and return the head of the sorted list. Each node holds a value val and a pointer next to the node after it, and the last node points to null. As a follow-up, can you sort it in O(n log n) time for n nodes, using only a constant amount of extra memory?

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

The Idea

Sorting a hand of cards is easy when you can spread them out and pick up any card you like. A linked list does not let you do that. You hold only the first node, and you reach any other node by following next pointers one at a time. A sort that jumps to the middle, or swaps two far-apart values, has to walk there first.

So what can a linked list do cheaply? It can cut itself in two by setting one node's next to null. It can also join two sorted lists into one sorted list, just by relinking nodes. This joining is called merging. To merge 2 -> 4 with 1 -> 3, compare the two front nodes, 2 and 1, and take the smaller one, 1. Then compare 2 and 3 and take 2, then 3, then 4.

Merging needs sorted lists to start with, so where do they come from? A list of one node is already sorted. Call a sorted stretch of nodes a run. Every node on its own is a run of length 1, and two runs of 1 merge into a run of 2. Look at the picture below.

The list 4, 2, 1, 3 sorted in rounds. Round 1 merges [4] and [2] into 2, 4, and [1] and [3] into 1, 3. Round 2 merges the runs [2, 4] and [1, 3] into 1, 2, 3, 4.

The top row is Example 1, 4 -> 2 -> 1 -> 3, seen as four runs of 1. The first round merges [4] and [2] into 2, 4, and merges [1] and [3] into 1, 3. That gives the row labelled "after round 1": two sorted runs of 2. The second round merges run [2, 4] with run [1, 3], and the bottom row is the whole list in order.

Each round doubles the run length: 1, then 2, then 4, until one run covers the whole list. Sorting by merging ever larger sorted pieces is called merge sort. Starting from the smallest runs and working upward, as in the picture, is its bottom-up form.

The number of nodes does not have to be a power of two. Example 2 has five nodes, so in the first two rounds the last node, 0, has no partner run. It stays at the end, and the third round, with runs of 4, merges it with the other four nodes.

Solution Approach

Four decisions turn these rounds into code: why merge sort fits a linked list, how many rounds to run, how to cut and merge the runs of one round, and how to link the merged runs back into one list. The recursive form of merge sort is an optional alternative.

Why merge sort fits a linked list

Why not a simpler sort? The simplest way to sort a linked list takes the nodes one by one and walks from the head to find each one's place. For a list that is already in order, every node walks past all the nodes placed before it, so the work grows with n². Copying the values into an array and sorting that is fast, but the array takes memory for all n values, which the follow-up rules out.

Other fast sorts suit a list badly too. Heap sort keeps the values in an array shaped like a tree and keeps jumping between far-apart positions, which a list can only reach by walking. Quick sort splits the values around one chosen value, and on a list it can still take O(n²) time when those splits come out uneven. Merge sort only cuts lists and merges them, and both are cheap on a list.

Counting the rounds

When is the list sorted? As soon as one run is at least as long as the whole list. So first count the nodes into n. Then let the run length size take the values 1, 2, 4 and so on, and stop once size reaches n. A list of zero or one node needs no round at all.

Cutting and merging the runs of one round

How does one round find its runs? It walks the list from the front. It cuts off size nodes as the left run, then up to size nodes as the right run, and keeps a pointer to whatever comes after them. Near the end of the list the right run may be shorter, or empty, and that is fine.

The two runs are then merged, exactly as two sorted lists are in Merge Two Sorted Lists. Taking the left node when the two values are equal keeps equal values in their original order, which makes the sort stable.

Linking the merged runs back together

Where does each merged run go? Right after the run merged before it, so the list stays in one piece. A pointer tail keeps the last node of the list built so far in this round, and the next merge attaches its nodes after tail.

The very first run has no node in front of it. A spare node placed before the head, called a dummy node, solves that: the first merge attaches after the dummy, and the sorted list always starts at the dummy's next.

Optional: the recursive version

Merge sort is often written top-down instead. Find the middle of the list with two pointers, one moving one node at a time and one moving two, cut the list there, sort each half with a recursive call, and merge the halves. That is shorter to write and also takes O(n log n) time.

Each recursive call that has not finished yet keeps a small record in memory, on the call stack. The halves get halved about log2 n times, so the stack holds up to about log2 n records. That memory grows with n, so it misses the follow-up's constant-memory goal, which the bottom-up rounds meet.

Java Solution

Here is what sortList does, in the order the code runs:

  1. First, walk the list once and count its nodes into n.
  2. Create a dummy node, dummy, whose next is head.
  3. An outer loop runs the rounds, with size going 1, 2, 4 and so on while it is less than n. Each round starts with tail on dummy and rest on the first node of the list.
  4. Inside, a while loop takes pairs of runs until rest is null. The left run, left, starts at rest. The helper split(left, size) cuts it after size nodes and returns the next node, the start of the right run, right. A second split(right, size) cuts that run and moves rest to what follows it.
  5. The helper merge(left, right, tail) links the smaller front node after tail again and again, then attaches whatever is left of the other run. It walks to the end of the merged run and returns that last node as the new tail.
  6. After the last round, return dummy.next.

The class also has a small ListNode class, a build helper that turns values into a list, and a show helper that prints a list as [1, 2, 3]. The main method runs the three examples, a single node, a list with repeated values, and a list in reverse order.

Java
public class SortList {

    static class ListNode {
        int val;
        ListNode next;

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

    public static ListNode sortList(ListNode head) {
        int n = 0;
        for (ListNode p = head; p != null; p = p.next) {
            n++;
        }
        ListNode dummy = new ListNode(0, head);
        for (int size = 1; size < n; size *= 2) { // merge sorted runs of length size
            ListNode tail = dummy;
            ListNode rest = dummy.next;
            while (rest != null) {
                ListNode left = rest;
                ListNode right = split(left, size);  // left has size nodes
                rest = split(right, size);           // right has up to size nodes
                tail = merge(left, right, tail);     // append the merged run
            }
        }
        return dummy.next;
    }

    // Cut the list after count nodes; return the start of the rest.
    private static ListNode split(ListNode head, int count) {
        for (int i = 1; head != null && i < count; i++) {
            head = head.next;
        }
        if (head == null) {
            return null;
        }
        ListNode rest = head.next;
        head.next = null;
        return rest;
    }

    // Merge two sorted lists after tail; return the new tail.
    private static ListNode merge(ListNode a, ListNode b, ListNode tail) {
        while (a != null && b != null) {
            if (a.val <= b.val) {
                tail.next = a;
                a = a.next;
            } else {
                tail.next = b;
                b = b.next;
            }
            tail = tail.next;
        }
        tail.next = (a != null) ? a : b;
        while (tail.next != null) {
            tail = tail.next;
        }
        return tail;
    }

    static ListNode build(int... values) {
        ListNode head = null;
        for (int i = values.length - 1; i >= 0; i--) {
            head = new ListNode(values[i], head);
        }
        return head;
    }

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

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

Running it prints:

Output
[1, 2, 3, 4]
[-1, 0, 3, 4, 5]
[]
[7]
[1, 1, 1, 2, 2, 3, 3]
[1, 2, 3, 4, 5, 6]

Look at the second line, [-1, 0, 3, 4, 5]. Its five nodes take three rounds, with size 1, 2 and 4. The 0 has no partner run until the last round, so it moves to second place only then. The empty list prints [] and the single node prints [7]: with n at 0 or 1, the outer loop never runs and dummy.next is the list as it came in.

The line [1, 1, 1, 2, 2, 3, 3] comes from seven nodes with repeats, so its last round merges a run of 4 with a run of only 3. The reversed list 6, 5, 4, 3, 2, 1 also takes just three rounds and prints [1, 2, 3, 4, 5, 6].

The loop at the end of merge, which walks tail to the last node, matters. Without it, tail stays on the last node the comparisons took. In round 1 of Example 1, merging [4] and [2] leaves tail on 2, with 4 attached after it. The next merge then links 1 after 2 and cuts the 4 off. With that loop removed, Example 1 prints [2, 1, 3].

Complexity

The work is one counting walk, then a series of rounds that each walk the whole list.

  • Time: O(n log n). The run length doubles every round, so the n nodes need about log2 n rounds, rounded up: three for the five nodes of Example 2. In each round, split and merge together pass over every node a small, fixed number of times.
  • Space: O(1). The method keeps only a few pointers (dummy, tail, rest, left, right) and relinks the existing nodes. There is no array copy, and the rounds replace recursion, so no call stack grows with n.

The same idea on an array, where merging needs a second array, is explained in Merge Sort.