Merge Two Sorted Lists
Master this topic with zero to advance depth.
Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
Visual Representation
L1: 1 -> 2 -> 4
L2: 1 -> 3 -> 4
Result: 1 -> 1 -> 2 -> 3 -> 4 -> 4Examples
Level I: Iterative
Intuition
Use a dummy node and a tail pointer. Compare the heads of both lists, attach the smaller node to the tail, and move pointers forward.
Visual Pointer Walk
L1: [1] -> [3]
L2: [2] -> [4]
1. Compare 1 and 2. Attach 1. Tail=[1], L1=[3]
2. Compare 3 and 2. Attach 2. Tail=[2], L2=[4]
3. Compare 3 and 4. Attach 3. Tail=[3], L1=null
4. Attach remaining L2: Tail points to [4].Detailed Dry Run
L1: 1->2, L2: 1->3. Dummy -> 1 (L1) -> 1 (L2) -> 2 (L1) -> 3 (L2).
⚠️ Common Pitfalls & Tips
Don't forget to attach the remaining nodes at the end.
Level III: Optimized In-place (No Dummy)
Intuition
Merge the lists in-place by always picking the smaller node as the current head and moving pointers. This avoids the use of a dummy node by handling the first node comparison separately.
Detailed Dry Run
L1: 1->3, L2: 2->4.
- L1.val (1) < L2.val (2). Result head is 1.
- Iterate and link nodes in-place.
⚠️ Common Pitfalls & Tips
Must handle the head assignment carefully to avoid null pointer exceptions.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.