Merge Two Sorted Lists
Merge two sorted linked lists into one sorted list in O(n + m) time and O(1) space by splicing existing nodes.
01The problem
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted linked list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
| Input | Output | Why |
|---|---|---|
list1 = [1, 2, 4], list2 = [1, 3, 4] | [1, 1, 2, 3, 4, 4] | Nodes interleaved in sorted order |
list1 = [], list2 = [] | [] | Both lists empty |
list1 = [], list2 = [0] | [0] | Merging with an empty list leaves the other unchanged |
list1 = [5], list2 = [1, 2, 4] | [1, 2, 4, 5] | All elements of list2 precede list1 |
Constraints: 0 to 50 nodes per list, node values between -100 and 100, both lists sorted in non-decreasing order.
Loading the rest of the lesson…