Merge Two Sorted Linked Lists
Join two sorted linked lists into one sorted list by relinking their nodes, smaller front first.
Two linked lists, list1list2
Example 1
Output: [1, 1, 2, 3, 4, 4]
Example 2
Output: []
Example 3
Output: [0]
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 nextnextnulllist1list2next
In Example 1, list1list2list1list2
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 list1list2
After that the fronts are 4 and 4, the 4 from list1list1list2list2list2
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 nexttailtaildummy.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 <=list1
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.nextlist1list2
Java Solution
The method mergeTwoLists
- First, create the placeholder node
and pointdummy at it.tail - The parameters
andlist1 serve as the two fronts: each points at the first node of its list not yet merged. Loop while neither of them islist2 .null - In each pass, compare the fronts with
. Link the smaller node tolist1.val <= list2.val and move that list's front to its next node. Then movetail.next onto the node just linked.tail - After the loop, set
to whichever list still has nodes, or totail.next if both are empty.null - Return
, the first real node of the merged list.dummy.next
Besides the method, the class holds a minimal ListNodebuildshow[1, 2, 3]mainlist1list2list1
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:
[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]list2list2list1[1, 2][1, 1, 2, 3, 4]
The [][0]dummy.nextnull
The last line, truelist1list1<<=falselist2
The original implementation and its tests are on GitHub:
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
. The merged list is built from the input nodes themselves, so the extra memory stays the same for lists of any length.dummy
This merge is also the second half of