Merging and sorting
Merging two sorted lists means repeatedly taking the smaller front node and appending it to a tail behind a dummy head. With that one step, lists can be merge-sorted in O(n log n) without extra arrays, many columns can be flattened, and common values can be found in one pass.
How to recognise it
- Two or more sorted lists must be combined into one sorted list.
- A list must be sorted in O(n log n), possibly with O(1) extra memory apart from recursion.
- The question asks for values common to two sorted lists.
The idea in one picture
Two queues of people sorted by height merge into one sorted queue by letting the shorter of the two front people step
forward each time. A dummy head node is the empty spot where the new queue starts, and tail is its current end.
Template: merge two sorted lists
dummy = new node, tail = dummy
while a is not null and b is not null:
if a.val <= b.val: tail.next = a; a = a.next
else: tail.next = b; b = b.next
tail = tail.next
tail.next = a if a is not null else b
return dummy.next
No nodes are created: the existing nodes are relinked.
Built on merging
| Problem | How merging is used |
|---|---|
| Sort List | split at the middle, sort both halves, merge them (merge sort) |
| Flattening a list of columns | flatten everything to the right, then merge this column in |
| Intersection of sorted lists | the same two-front walk, but keep only equal fronts |
| Quicksort for lists | the opposite idea: split by a pivot into three chains, sort, then join |
Common mistakes
- Forgetting to attach the leftover part of the longer list.
- Not cutting the list in half before recursing, which recurses forever.
- Creating new nodes when relinking is enough (except where the question asks for a new list).
- Using the first node as the quicksort pivot without three-way splitting, which is slow on many equal values.
Problems
- Merge Two Sorted Listseasyguide ready
- Flattening of LLmediumguide ready
- Sort Listmediumguide ready
- Intersection of two Sorted Linked Listmediumguide ready
- Quicksort for Linked Listsmediumguide ready