Problem
Given the heads of two sorted linked lists, merge them into one sorted list made by splicing together the existing nodes, and return its head.
Approach
Start from a dummy node so the head of the merged list needs no special case.
Compare the current nodes of both lists, attach the smaller one to the result, and advance that list. When one list runs out, attach the rest of the other list in one step, since it is already sorted.
The solution files below implement this approach in C++, Python and TypeScript.
Complexity
- Time: O(n + m).
- Space: O(1): the existing nodes are relinked, not copied.
Edge cases
- Either list can be empty.
- Equal values can come from either list; taking from the first keeps the merge stable.