merge_two takes from b only when b.val < a.val. Of the three 4s, which come first?
Pick one to see what it prints.
No new nodes are made: the result is the old nodes, relinked. Here each node keeps its column from the result, and the two 4s from a come before the 4 from b:
The merged list
a
1
→
4
→
4
→
9
→None
b
2
→
4
→
10
→None
out
1
→
2
→
4
→
4
→
4
→
9
→
10
→None
No new nodes: the result relinks the old ones. Orange nodes came from b.
That's O(m + n) time and O(1) memory. A recursive version is shorter to write, and it makes one call per node:
def merge_two_recursive(a, b): if a is None or b is None: return a if a is not None else b if b.val < a.val: b.next = merge_two_recursive(a, b.next) return b a.next = merge_two_recursive(a.next, b) return a
Merging the even numbers below 1,000 with the odd ones, two lists of 500 nodes, it raised RecursionError.
In the editor, write merge_two(a, b), the function the code above calls, with a loop. It merges the same two lists.
Pick an answer above to see the rest
Instructions
1
Write merge_two(a, b): relink the nodes of two sorted lists into one sorted list and return its head, making no new nodes except a dummy head.
2
On a tie take from a first, so the merge is stable, and use a loop: the lists can be long.