Sub topic 13
Merging two sorted lists
This chapter assumes you can traverse a singly linked list, know what a sentinel (dummy) node is, and can read introductory Big-O notation. The code is Python.
The problem
You have two linked lists, each sorted in ascending order. You want one sorted list that contains every node from both. This is the merge step of merge sort, and it is a common interview problem.
The method is the same as merging two sorted decks of cards. Compare the front card of each deck, take the smaller one, and repeat. When one deck is empty, put the rest of the other deck on the end.
Why a dummy node helps
The first node of the result is either a or b. Without a sentinel, you need a special case to set the result's head. A dummy node removes that case. Every real node is attached with tail.next = ..., and the answer is dummy.next.
The code
The merge_sorted function is the one from the plan. The helpers from_list and to_list exist only so you can run and check it.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def from_list(values):
dummy = Node(None)
tail = dummy
for v in values:
tail.next = Node(v)
tail = tail.next
return dummy.next
def to_list(head):
out = []
while head is not None:
out.append(head.value)
head = head.next
return out
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
merged = merge_sorted(from_list([1, 4, 7]), from_list([2, 4, 9, 10]))
print(to_list(merged)) # [1, 2, 4, 4, 7, 9, 10]How it works
The loop keeps two facts true. Everything from dummy.next up to tail is sorted and final. Every value still in a or b is at least as large as tail.value.
When the loop ends, at least one list is empty. The other list is already sorted and all its values are at least as large as tail.value. So one assignment, tail.next = a if a is not None else b, attaches the whole remainder. You do not copy it node by node.
Cost
- Time is O(n + m), where n and m are the list lengths. Each loop pass moves one node into the result.
- Extra space is O(1). The function creates one dummy node and relinks the existing nodes. It does not allocate new ones.
The second point has a consequence. After the merge, a and b no longer describe the original lists, because their nodes now belong to the merged list. If you still need the originals, copy them first.
Common errors
- Returning
dummyinstead ofdummy.next. The result then starts with aNonenode. - Forgetting
tail = tail.nextafter attaching a node. Each new node overwrites the previous one, and you lose nodes. - Looping with
orinstead ofand. One list runs out first, and you then read.valueonNone. - Attaching the remainder inside the loop. Do it once, after the loop ends.
- Passing unsorted input. The function does not check, so the output is silently wrong.
Exercise
What does merge_sorted return if a is None and b is the list 1 -> 2? Which line produces that result, and how much work does the function do?
Show answer
It returns the list 1 -> 2. The while loop never runs, because a is None. The line tail.next = a if a is not None else b then sets dummy.next to b, and the function returns dummy.next. The work is constant: one dummy node and one assignment.
Exercise
Change merge_sorted so that it merges two lists sorted in descending order into one descending list. What is the smallest edit?
Show answer
Change the comparison from a.value <= b.value to a.value >= b.value. The rest of the code stays the same, because the loop always attaches whichever front node should come first.