Merge Two Sorted Lists
Problem
You are given the heads of two linked lists, each already sorted in non-decreasing order. Combine them into a single sorted list by reusing the existing nodes (no new nodes, and no rebuilding from scratch) and return its head.
Example. Merging 1 -> 2 -> 4 with 1 -> 3 -> 4 produces 1 -> 1 -> 2 -> 3 -> 4 -> 4.
Key idea
Because both inputs are already sorted, there is no need to collect every value and sort them again: that would cost an unnecessary O((n+m) log(n+m)) when the lists already carry the ordering information. Instead, walk both lists at once and compare only the two nodes currently at the front. Splice whichever one is smaller onto the result, then advance that list's pointer by one; the other pointer stays put for the next comparison.
A dummy placeholder node before the real result avoids special-casing which list contributes the first node: everything gets appended after the dummy, and the answer is the node after it. Once one list runs dry, the remaining list is already sorted, so its remainder can be attached directly rather than walked node by node.
Solution
Complexity
- Time: O(n + m). Each node from both lists is visited and compared exactly once.
- Space: O(1) beyond the output. Existing nodes are relinked rather than copied, aside from the small overhead of the dummy node.
Watch out for
- Compare node values, not node references, and remember
<=and<both work as long as the tie-break is consistent. - After the loop ends, attach whichever list still has nodes left directly: looping element by element for the remainder is unnecessary and easy to get wrong.
- Do not forget to detach the dummy node before returning; the answer is
dummy.next, notdummyitself.
Pattern
This two-pointer merge is the core building block of merge sort and generalizes directly to combining more than two sorted sequences, as in merging k sorted lists.