Problem overview
The method mergeTwoLists receives list1 and list2, the heads of two singly linked lists that are each sorted in ascending order. It returns the head of one sorted list that holds all the nodes of both. The lesson provides the ListNode class: each node has a val and a next that points to the following node, or is null at the end of a list. An empty list is represented by null.
The merged list must be made of the existing nodes, linked to each other, not of copies. For list1 = [1,2,4] and list2 = [1,3,4] the result is [1,1,2,3,4,4]. When two front nodes hold equal values, the one from list1 goes first.
Approach
Both lists are sorted, so the smallest value that has not been placed yet is always one of the two front nodes. Compare them, take the smaller one, and repeat. This is the merge step of merge sort, done on linked nodes.
Taking a node means re-linking it: the merged list's last node gets its next set to the chosen node, and the chosen list moves one node forward. No node is created or copied, so the extra space is O(1), and each node is handled once, so the time is O(n + m) for lists of length n and m.
There are two decisions worth understanding:
- A dummy node. The head of the merged list is not known until the first comparison. Starting from a placeholder node in front of it means that attaching the first real node is the same operation as attaching every later one. The answer is the node after the placeholder.
- A loop, not recursion. A recursive merge adds one call to the stack per node. With up to 10,000 nodes in each list that is 20,000 nested calls, which can exceed the call stack. The loop uses constant space.
Step by step
- Create the placeholder.
dummyis a newListNode. It is declared withconstbecause the variable always names the same node; its fields still change. Its own value is never used. - Track the end of the merged list.
tailstarts atdummyand is declared withlet, because it moves forward. It always points at the node that the next one will be attached to. - Loop while both lists have nodes. Only then is there a comparison to make. The test uses
!== nullon both lists. - Pick the smaller front node. If
list1.val <= list2.val, attachlist1totail.nextand movelist1tolist1.next. Otherwise do the same withlist2. The<=is what puts the node fromlist1first on a tie, so equal values keep their original order. - Advance
tail. Both branches attach a node attail.next, so one line after theif/elsemovestailonto it. - Attach the leftovers. When the loop ends, at least one list is empty. The other still holds sorted nodes that are all at least as large as everything merged so far, so the whole remainder is linked in one assignment, without more comparisons. If
list1is notnullit is the remainder; otherwiselist2is, and if both are empty that isnull, which ends the list correctly. - Return
dummy.next. The placeholder is not part of the answer.
The solution in TypeScript
class Solution {
mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
const dummy = new ListNode();
let tail = dummy;
while (list1 !== null && list2 !== null) {
if (list1.val <= list2.val) {
tail.next = list1;
list1 = list1.next;
} else {
tail.next = list2;
list2 = list2.next;
}
tail = tail.next;
}
tail.next = list1 !== null ? list1 : list2;
return dummy.next;
}
}
Some details for TypeScript:
- Parameters can be reassigned.
list1andlist2are ordinary local variables, so the loop moves them along their lists. The caller's variables are not affected, but the nodes themselves are shared: the returned list is built from the very nodes that were passed in. - The types are checked only by the compiler.
ListNode | nulldocuments that a list may be empty, but nothing is checked when the program runs; the loop's!== nulltests are what actually protectlist1.valandlist2.val. - The conditional operator
condition ? a : bgivesawhen the condition is true andbotherwise, which makes the leftover step a single line. - Nodes are reused. Merging the lists
1 → 3and2returns the original first node of the first list, and itsnextis the original node of the second list.
Complexity
Time: O(n + m). Each loop turn moves one node from an input list into the merged list, and the leftover is attached in one step. Space: O(1). The code keeps only dummy, tail and the two moving pointers, and creates one node in total.
Edge cases and common mistakes
- Both lists empty. The loop does not run,
tail.nextis set tolist2, which isnull, anddummy.nextisnull: an empty list. - One list empty. With
list1 = []andlist2 = [0]the loop is skipped and the leftover step returns the second list as it is. - One list much shorter. For
[-4,10,12]and[-7,0]the second list runs out after the three comparisons that place-7, -4, 0, and10 → 12is attached whole. - Forgetting the leftover step. The loop stops as soon as one list is empty, so without the final attach the rest of the other list is lost.
- Returning
dummyinstead ofdummy.next. The result would start with an extra node of value 0. - Forgetting to move
tail. Each new node would overwrite the previous one's place and the merged list would keep only the last node.
Testing
These inputs, run through the method, give:
| list1 | list2 | Result |
|---|---|---|
[1,2,4] | [1,3,4] | [1,1,2,3,4,4] |
[] | [0] | [0] |
[-4,10,12] | [-7,0] | [-7,-4,0,10,12] |
[] | [] | [] |
[5] | [] | [5] |
[1,1] | [1,1] | [1,1,1,1] |
Two lists of 10,000 nodes each (the even and the odd numbers) merge into one sorted list of 20,000 nodes without any trouble.
