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
- Both lists are already sorted. Compare their front items.
- Take the smaller one, append it to the result, and advance in that list.
- Repeat until one list is empty, then attach the rest of the other (it is already sorted).
- Each node is touched once: O(n + m), and no new nodes are created.
Watch it run
Loading animation…