Sub topic 13
Merging two sorted lists
Merging combines two sorted linked lists into one sorted list. It is the "merge" step of merge sort, and it shows how a sentinel node and careful pointer updates keep list code short.
This chapter assumes you can read the Node class from earlier chapters, know why a sentinel (dummy) node removes head special cases, and can reason about O(n) time and O(1) extra space.
The problem
You are given the heads of two lists, each sorted in ascending order. Return the head of one list that contains every node, still in ascending order.
The key observation is that the smallest remaining value is always at the front of one of the two lists. You never need to look deeper. At each step you compare two values, take the smaller node, and move forward in the list it came from.
This works because each list is already sorted. If either input is unsorted, the output is not sorted either, and nothing raises an error.
The working model: a tail pointer on a growing result
Build the result by keeping a tail pointer at the last node of the merged list. Each step does three things:
- Compare the front nodes of
aandb. - Link the smaller one after
tail. - Advance the list you took it from, and advance
tailonto the node you just attached.
The first node of the result has no predecessor, so tail.next has nothing to attach to. A dummy node solves this. It is a throwaway node that starts as tail, so every attachment looks the same, including the first. When you finish, the real head is dummy.next.
The implementation
This version is complete and runnable. The from_list and to_list helpers exist only so you can build test inputs and print results.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def merge_sorted(a, b):
dummy = Node(None)
tail = dummy
while a is not None and b is not None:
if a.value <= b.value:
tail.next = a
a = a.next
else:
tail.next = b
b = b.next
tail = tail.next
tail.next = a if a is not None else b
return dummy.next
def from_list(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_list(head):
out = []
while head is not None:
out.append(head.value)
head = head.next
return out
merged = merge_sorted(from_list([1, 4, 7]), from_list([2, 3, 9]))
print(to_list(merged)) # [1, 2, 3, 4, 7, 9]Tracing one run
The table shows the state after each loop iteration for a = 1 → 4 → 7 and b = 2 → 3 → 9.
| Step | Compared | Attached | Result so far | Remaining a | Remaining b |
|---|---|---|---|---|---|
| 1 | 1 vs 2 | 1 (from a) | 1 | 4 → 7 | 2 → 3 → 9 |
| 2 | 4 vs 2 | 2 (from b) | 1 → 2 | 4 → 7 | 3 → 9 |
| 3 | 4 vs 3 | 3 (from b) | 1 → 2 → 3 | 4 → 7 | 9 |
| 4 | 4 vs 9 | 4 (from a) | 1 → 2 → 3 → 4 | 7 | 9 |
| 5 | 7 vs 9 | 7 (from a) | 1 → 2 → 3 → 4 → 7 | empty | 9 |
The loop stops because a is empty. The line after the loop sets tail.next = b, which attaches the whole remaining chain 9 in one assignment. You do not copy the leftover nodes one at a time. They are already linked in order.
Why each detail matters
The leftover line
When the loop ends, at most one list still has nodes. Every value in that remainder is greater than or equal to everything already attached, because the other list's last node was chosen over it. The expression a if a is not None else b picks whichever is non-empty. If both are empty, it assigns None, which is correct and harmless.
Why `<=` and not `<`
On ties, <= takes the node from a first. Equal values from a therefore stay ahead of equal values from b, and the merge is stable. Stability matters when nodes carry more than the sort key. For example, merging records sorted by date, where a holds the older batch. With <, tied nodes from b would jump ahead.
Time and space
Each iteration attaches exactly one node and advances one of the two lists, so the loop runs at most n + m times for lists of length n and m. The time is O(n + m). The extra space is O(1): one dummy node and a few references. No new data nodes are created, because the merge relinks the existing ones.
Common errors
- Returning
dummyinstead ofdummy.next. The result then starts with aNonevalue node, which breaks later comparisons and printing. - Forgetting
tail = tail.next. Every attachment then overwrites the sametail.next, and the result keeps only the last node attached. - Forgetting the leftover line. The output silently loses the tail of the longer list. Tests with equal-length lists will not catch this, so test with lists of different lengths.
- Merging unsorted input. The algorithm cannot tell. Check or sort the input first if you do not control its source.
- Passing the same list for both arguments, or lists that share nodes. Relinking a node into the result while the other pointer still reaches it can create a cycle.
merge_sorted(a, a)loops forever.
Without a dummy node
For comparison, here is the same merge with the head handled as a special case.
def merge_sorted_no_dummy(a, b):
if a is None:
return b
if b is None:
return a
if a.value <= b.value:
head = a
a = a.next
else:
head = b
b = b.next
tail = head
while a is not None and b is not None:
if a.value <= b.value:
tail.next = a
a = a.next
else:
tail.next = b
b = b.next
tail = tail.next
tail.next = a if a is not None else b
return headIt works, but the choose-and-advance logic appears twice. Any change to the comparison must be made in both places. The sentinel version has one copy.
A recursive version
The merge also has a recursive form. The smaller front node becomes the head, and its next is the merge of the rest.
def merge_recursive(a, b):
if a is None:
return b
if b is None:
return a
if a.value <= b.value:
a.next = merge_recursive(a.next, b)
return a
b.next = merge_recursive(a, b.next)
return bThis is short, but it uses one stack frame per node. Python's default recursion limit is about 1000, so lists with a few thousand nodes raise RecursionError. The iterative version has no such limit, and it is the one to use in production code.
Extension: merging k lists
To merge k sorted lists, a pairwise approach would rescan the growing result repeatedly. A min-heap keeps one front node per list and always pops the smallest.
import heapq
def merge_k(lists):
dummy = Node(None)
tail = dummy
heap = [(n.value, i, n) for i, n in enumerate(lists) if n is not None]
heapq.heapify(heap)
while heap:
_, i, node = heapq.heappop(heap)
tail.next = node
tail = node
if node.next is not None:
heapq.heappush(heap, (node.next.value, i, node.next))
return dummy.nextThe middle tuple element i is a tie-breaker. Without it, two entries with equal values make Python compare the Node objects, which raises TypeError because Node defines no ordering. With N total nodes, the cost is O(N log k) time and O(k) extra space.
Where this is used
Merge sort on linked lists uses this routine as its combine step. Splitting a list in half uses the slow and fast pointers from earlier in this tutorial, and the merge then runs without any random access. That is why merge sort is a natural fit for linked lists, where indexing into the middle is expensive.
Exercise
Merge a = 1 → 3 → 5 and b = 2 → 3 → 4 with merge_sorted as written. Give the resulting values in order, and say which list the first 3 in the output came from.
Show answer
The result is 1, 2, 3, 3, 4, 5. The comparison 3 <= 3 is true, so the first 3 comes from a. This is the stable behavior produced by <=. The leftover line then attaches the remaining chain from a (5) after the loop ends.
Exercise
A test merges [1, 2, 3] with [4, 5, 6] and passes, but merging [1, 5, 9, 10] with [2, 3] returns [1, 2, 3] only. What bug does this point to, and why did the first test not catch it?
Show answer
The line tail.next = a if a is not None else b is missing. In the first test, list a runs out first, so b = 4 → 5 → 6 is never attached either, but a missing leftover would give [1, 2, 3] there too. A test that does pass with the line missing is one where both lists are drained inside the loop, which is not possible here. The point is that the leftover line is always required, and a test with lists of unequal length, such as the second one, is what exposes its absence. Here, once b is empty, the nodes 5 → 9 → 10 from a should be attached in one assignment, and without that line they are lost.