The input is list1 and list2, the heads of two linked lists. Both lists are sorted, smallest value first. Merge them into one sorted list, made of their own nodes, not copies. Return the head of the merged list.
0 <= each list's length <= 50
-100 <= Node.val <= 100
Both lists are sorted ascending.
Prerequisites
Linked lists — a node holds a value and a next reference, and rearranging a list means moving references, never values. Dummy heads: a node in front of the list so the first element stops being a special case. Two pointers on a list — one ahead of the other, or one moving twice as fast.
How to think about it
1. Dummy Head and a Tail Pointer Optimal
Intuition
Both lists are sorted, so the smallest remaining node is always at the front of one of them — take it, advance that list, repeat. The awkward part is the very first node, since there is no tail to attach it to yet; a dummy node in front removes that case entirely, and the answer is whatever it ends up pointing at.
Algorithm
1. Make a dummy node and let tail point at it. 2. While both lists have nodes, attach the smaller front and advance that list. 3. Attach whichever list still has nodes — it is already sorted and already larger. 4. Return dummy.next.
Time & Space
Time O(n + m). Space O(1): the nodes are spliced, not copied.
2. Recursion: The Smaller Front, Then the Rest
Intuition
An empty list merged with another is the other list. Otherwise the smaller of the two fronts, list1's on a tie, is the head of the merged list, and its next is the merge of everything after it with the other list: the same problem, one node smaller. Each call takes one node and leaves the rest to the next call, and the nodes are linked as the calls return.
Algorithm
1. If list1 is empty, return list2. 2. If list2 is empty, return list1. 3. If list1's front is smaller or equal, set list1.next to the merge of list1.next and list2, and return list1. 4. Otherwise set list2.next to the merge of list1 and list2.next, and return list2.
Time & Space
Time O(n + m). Space O(n + m): a call waits on the stack for every node it takes. The constraints allow 50 nodes a list, so at most 100 calls. In Python the stack ends at about 1,000 calls, so lists of about 1,000 nodes between them, far past the constraints, stop with RecursionError.