Learn / Linked lists

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

ProblemHow merging is used
Sort Listsplit at the middle, sort both halves, merge them (merge sort)
Flattening a list of columnsflatten everything to the right, then merge this column in
Intersection of sorted liststhe same two-front walk, but keep only equal fronts
Quicksort for liststhe 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

0 of 5 solved

Check yourself

When merging, why use <= rather than < when the two front values are equal?

How does merge sort split a linked list in half?

When finding values common to two sorted lists, which front do you advance when they differ?