1578. Interleave Two Chains
Two lanes of cars approach a merge point, and they must enter the single lane in strict alternation. You receive two singly linked lists a and b. Relink their existing nodes into one list ordered a1, b1, a2, b2, and so on, always starting with the first node of a. As soon as one list runs out, attach the whole remainder of the other list at the end. If a is empty the answer is simply b, if b is empty it is a, and if both are empty it is null. Do not create new nodes. Return the head of the combined list. Each list has 0 to 1000 nodes. Aim for O(n + m) time and O(1) extra space.
Example 1
- Input:
- a = [1,3,5], b = [2,4,6]
- Output:
- [1,2,3,4,5,6]
- Explanation:
The lists alternate a1,b1,a2,b2,a3,b3.
Example 2
- Input:
- a = [1,2,3,4], b = [9]
- Output:
- [1,9,2,3,4]
- Explanation:
After b runs out the rest of a follows.
Example 3
- Input:
- a = [], b = [5,6]
- Output:
- [5,6]
- Explanation:
With an empty a, the answer is b.
Constraints
0 ≤ length of a, length of b ≤ 1000
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n + m)
- Space
- O(1)