Given the heads of two sorted linked lists, merge them into one sorted list made by splicing together the existing nodes, and return its head.
Before you code
Without a dummy head, the first node of the result is a special case: you have to decide which list it comes from before the loop. With one, the loop is the same from the first node to the last.
Hints
- Create
dummyand settail = dummy. - While both lists have nodes, attach the smaller head to
tail.next, advance that list, and advancetail. - When one list runs out, attach the rest of the other in one step:
tail.next = l1 or l2. - Return
dummy.next. No new nodes are created apart from the dummy.
Production & complexity notes
When solving Merge two sorted lists on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Insert, delete and the dummy head to reinforce the underlying pattern.
What it practices
The dummy head and pointer splicing, from Insert, delete and the dummy head.