Zip two sorted lists together
EasyStuck?
Show a hintHide the hint
Use a dummy head so the first node is not a special case, then repeatedly attach whichever list has the smaller front.
The idea behind this problem
Next in this lesson
Find the middle in one passGiven two sorted linked lists, splice them into one sorted list and return its head.
Worked example#
For 1 -> 2 -> 4 and 1 -> 3 -> 4, take the smaller head each time:
| left | right | take | built so far |
|---|---|---|---|
| 1 | 1 | 1 from the left | 1 |
| 2 | 1 | 1 from the right | 1 1 |
| 2 | 3 | 2 | 1 1 2 |
| 4 | 3 | 3 | 1 1 2 3 |
| 4 | 4 | 4 from the left | 1 1 2 3 4 |
| done | 4 | the rest of the right | 1 1 2 3 4 4 |
The answer is 1 1 2 3 4 4.
When one list runs out, the other is already sorted and already correct, so it can be attached whole rather than walked node by node.
The trick worth learning#
Building a list front to back means the first node is a special case: there is nothing to attach it to yet. Writing if (head == null) head = node; else tail.next = node; inside the loop works and is noisy.
Instead start with a dummy node that you throw away at the end. Every real node then has something to attach to, the loop has no special case, and the answer is dummy.next.
That trick is worth knowing because it applies to almost every problem that builds a linked list.
The cost#
Time O(n + m), one pass over each. Memory O(1), because no node is copied: the existing nodes are relinked.
Constraints#
0 <= nodes in each list <= 5000-1000 <= value <= 1000- Both lists are sorted in non-decreasing order
Input
list1 is a count then that many values. Then list2, written the same way.
Output
The merged list, values separated by spaces.
Examples
Input
3 1 2 4 3 1 3 4
Output
1 1 2 3 4 4
Take the smaller front each time, and ties can come from either side.
Input
0 0
Output
Two empty lists merge to an empty list.
Input
0 1 0
Output
0
One empty list means the answer is the other one.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.