Skip to content
StackDecode
Linked listsAnimated

Merge Two Sorted Linked Lists

Repeatedly attach the smaller head to the result.

Time

O(n + m)

Extra space

O(1)

Use it for

Building block of merge sort.

How it works

  1. Both lists are already sorted. Compare their front items.
  2. Take the smaller one, append it to the result, and advance in that list.
  3. Repeat until one list is empty, then attach the rest of the other (it is already sorted).
  4. Each node is touched once: O(n + m), and no new nodes are created.

Watch it run

Loading animation…