Merge Two Sorted Linked Lists

Join two sorted linked lists into one sorted list by relinking their nodes, smaller front first.

Two linked lists, list1 and list2, are each sorted from smallest to largest. Given their first nodes, merge them into one sorted list and return its first node. The merged list must be made from the nodes of the two lists, linked together in a new order, not from copies of their values.

Example 1
Input: list1 = [1, 2, 4], list2 = [1, 3, 4]
Output: [1, 1, 2, 3, 4, 4]
Example 2
Input: list1 = [], list2 = []
Output: []
Example 3
Input: list1 = [], list2 = [0]
Output: [0]
Solution

The Idea

Picture two piles of numbered cards, each sorted with its smallest card on top. To combine them into one sorted pile, you never have to look below the tops. The smallest card left is always one of the two top cards, so you take the smaller of them, put it on the new pile, and look at the two tops again.

Here the piles are linked lists. A linked list is a chain of nodes, where each node holds a value and a reference, named next, to the node after it. After the last card, next is null. The first node is called the head, and list1 and list2 point at the heads of the two lists. Changing a node's next links it to a different node, so nodes can move from one list to another without any value being copied.

In Example 1, list1 is 1, 2, 4 and list2 is 1, 3, 4. The two fronts are 1 and 1, a tie, and the 1 from list1 goes first. Next the fronts are 2 and 1, so the 1 from list2 follows. Then the fronts are 2 and 3, and 2 is smaller. Look at the picture below.

Merging list1 = 1, 2, 4 and list2 = 1, 3, 4, three nodes in. The merged list so far is 1, 1, 2. The front of list1 is 4 and the front of list2 is 3. 3 is smaller, so the last node, 2, is linked to the 3 next.

The picture shows the moment after those three steps. The row labelled merged so far holds 1, 1, 2, and the colors show which list each node came from. The front of list1 is now 4, and the front of list2 is 3, in orange. 3 is smaller than 4, so the dashed orange arrow links the last node, 2, to the 3.

After that the fronts are 4 and 4, the 4 from list1 goes next, and list1 has no nodes left. What about the 4 still waiting in list2? Nothing in list2 is smaller than the nodes already merged, and its nodes are in order already. So the whole rest of list2 can be linked on in one go, giving 1, 1, 2, 3, 4, 4.

So the merge needs one comparison per node: the smaller of the two fronts always goes next, and the nodes behind a front never need checking until they reach the front.

Solution Approach

A simple way skips the merge altogether, and it helps to see why it falls short. Then three things need settling: how to start the merged list, which node goes first on a tie, and what to do with the nodes left over when one list runs out.

Collecting and sorting the values

Why not copy every value into an array, sort it, and build a new list? It gives the right order, but sorting m + n values takes O((m + n) log(m + n)) time, where m and n are the numbers of nodes in the two lists. It also throws away the order the lists already have, and it builds new nodes, which the problem rules out. Comparing fronts uses that order and needs only one pass.

Starting the merged list

Where does each taken node go? It is linked after the last node of the merged list, through that node's next, and a variable named tail keeps hold of that last node. The very first node has nothing before it, so it would need code of its own. A placeholder node made before the loop, called a dummy node, avoids that: tail starts on the dummy, and the merged list begins at dummy.next.

Equal fronts

When the two fronts hold the same value, which node goes first? Either order gives a sorted list. The code compares with <=, so the node from list1 wins, as with the two 1s in Example 1. A merge that keeps equal values in their input order like this is called stable. It matters when the nodes carry more than a number, for example records sorted by date.

The nodes left over

What happens when one list runs out? A comparison needs two fronts, so the loop runs only while both lists still have a node. After it, at most one list has nodes left, and a single assignment to tail.next links all of them. Empty inputs need no extra code: if list1 is empty, the loop never runs and that assignment links all of list2.

Java Solution

The method mergeTwoLists works in these steps:

  1. First, create the placeholder node dummy and point tail at it.
  2. The parameters list1 and list2 serve as the two fronts: each points at the first node of its list not yet merged. Loop while neither of them is null.
  3. In each pass, compare the fronts with list1.val <= list2.val. Link the smaller node to tail.next and move that list's front to its next node. Then move tail onto the node just linked.
  4. After the loop, set tail.next to whichever list still has nodes, or to null if both are empty.
  5. Return dummy.next, the first real node of the merged list.

Besides the method, the class holds a minimal ListNode class and two helpers: build turns values into a list, and show prints a list as [1, 2, 3]. The main method runs the three examples and a list1 whose values are all bigger than those of list2. Last, it checks whether the merged list of Example 1 starts with the very node that was the head of list1.

Java
public class MergeTwoSortedLists {

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

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode(0);        // placeholder before the first node
        ListNode tail = dummy;                   // last node of the merged list so far
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {        // on a tie, list1 goes first
                tail.next = list1;
                list1 = list1.next;
            } else {
                tail.next = list2;
                list2 = list2.next;
            }
            tail = tail.next;
        }
        tail.next = (list1 != null) ? list1 : list2;   // attach whatever is left
        return dummy.next;
    }

    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) {
        ListNode a = build(1, 2, 4);
        ListNode merged = mergeTwoLists(a, build(1, 3, 4));
        System.out.println(show(merged));
        System.out.println(show(mergeTwoLists(build(), build())));
        System.out.println(show(mergeTwoLists(build(), build(0))));
        System.out.println(show(mergeTwoLists(build(5, 6, 7), build(1, 2))));
        System.out.println("first node is list1's head: " + (merged == a));
    }
}

Running it prints:

Output
[1, 1, 2, 3, 4, 4]
[]
[0]
[1, 2, 5, 6, 7]
first node is list1's head: true

Look at the fourth line, [1, 2, 5, 6, 7]. The 1 and 2 of list2 are both smaller than 5, so after two passes list2 is empty and the loop stops. All three nodes of list1 are then linked by the one assignment after the loop. Without that line, this input prints [1, 2], and Example 1 prints [1, 1, 2, 3, 4], losing its last 4.

The [] and [0] on the second and third lines are Examples 2 and 3. With an empty list the loop never runs, so the other list comes back as it is, or dummy.next stays null when both are empty.

The last line, true, says the merged list starts with the very node built as the head of list1. So no value was copied, and the tie between the two 1s went to list1. With < in place of <=, the list still prints the same, but this line prints false, because the 1 from list2 goes first.

The original implementation and its tests are on GitHub: MergeTwoSortedLists.java and TestMergeTwoSortedLists.java.

Complexity

The loop links one node per pass, and whatever is left over is joined in a single step.

  • Time: O(m + n) for lists of m and n nodes: every pass moves one of the two fronts forward by one node, so there are at most m + n passes, and linking the leftover costs one assignment however long it is.
  • Space: O(1). The only new node is dummy. The merged list is built from the input nodes themselves, so the extra memory stays the same for lists of any length.

This merge is also the second half of Sort List, which splits a list in two, sorts each half, and merges the halves the same way.