Merge Two Sorted Lists
Repeatedly take the smaller head and hang it on the merged tail. Relink instead of copying.
Merging Sorted Lists: Two lists, interleaving
Heads: 1 in a, 2 in b. The smallest is 1 from a, so it is unhooked from its list and linked after nothing: it becomes the merged head.
Cost
- Best
- O(n + m)
- Average
- O(n + m)
- Worst
- O(n + m)
- Space
- O(1)
Before this
Related
Leads to
Topics that need this one first.
Taught by the same lesson
Merging Sorted Lists covers these too, in the same run.