Problem Statement
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list by splicing together the nodes.
Intuition
Since both lists are already sorted, we only need to compare the current heads and always pick the smaller one. This naturally lends itself to a recursive or iterative approach.
Approach
- Use a dummy head node to simplify edge cases.
- Compare the heads of both lists.
- Attach the smaller node to the result and advance that list's pointer.
- When one list is exhausted, attach the remainder of the other.
Solution
TypeScript
function mergeTwoLists(
list1: ListNode | null,
list2: ListNode | null
): ListNode | null {
if (!list1) return list2;
if (!list2) return list1;
if (list1.val <= list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}
}
Complexity Analysis
| Metric | Value | Explanation |
|---|---|---|
| Time | Visit each node exactly once | |
| Space | Recursive call stack depth |