839. Merge two sorted linked lists
Two shards return their results as singly linked lists already sorted by score, ascending. You want one sorted list without copying values into an array.
A node class is provided: ListNode(val, next=None) with fields val and next. Write merge_sorted(a, b) that takes the two head nodes (either can be None) and returns the head of one merged sorted list built by relinking the existing nodes. When values are equal, nodes from a come first.
def merge_sorted(a, b)Example 1
Input: merging lists 1
Output: 3 -> 5 and 2 -> 4 gives 1 -> 2 -> 3 -> 4 -> 5
Example 2
Input: to_list(merge_sorted(build([1, 3, 5]), build([2, 4])))
Output: [1, 2, 3, 4, 5]
Example 3
Input: to_list(merge_sorted(build([]), build([1, 2])))
Output: [1, 2]
Constraints
- 0 <= length of each list <= 50,000
Hint 1
Start with dummy = tail = ListNode(0).
Hint 2
Take from a when values tie.
Hint 3
Attach the leftover list at the end.
Common mistakes
- Losing the rest of a list by moving the pointer before linking.
- Forgetting the leftover tail.
- Returning the dummy node instead of dummy.next.
Understand the idea
Merging two sorted sequences is the core step of merge sort and of k-way merges of shard results. With linked lists you relink nodes instead of copying, which keeps memory O(1). The dummy head is a standard trick: it gives the loop a node to attach to before the real head is known.