Merge two sorted lists
Easy TimeO(n + m) SpaceO(1)
Given the heads of two linked lists that are each already sorted ascending, splice them into one sorted list and return its head — [1, 3, 5] and [2, 4, 6] give [1, 2, 3, 4, 5, 6]. The result is built by relinking the existing nodes, not by copying values into a new list, and either list may be empty.
Examples
Example 1
- Input
- node = mergeTwoLists(buildList([1, 3, 5]), buildList([2, 4, 6]))
- Output
- Six values interleaved into one ascending run.
[1,2,3,4,5,6]
Example 2
- Input
- node = mergeTwoLists(buildList([]), buildList([2, 4]))
- Output
- One side is empty, so the other comes back whole and untouched.
[2,4]
The Code
function buildList(values) {
let head = null;
for (let i = values.length - 1; i >= 0; i--) {
head = { val: values[i], next: head };
}
return head;
}
function toArray(node) {
const out = [];
while (node) {
out.push(node.val);
node = node.next;
}
return out;
}
function mergeTwoLists(a, b) {
const dummy = { val: 0, next: null };
let tail = dummy;
while (a && b) {
if (a.val <= b.val) {
tail.next = a;
a = a.next;
} else {
tail.next = b;
b = b.next;
}
tail = tail.next;
}
tail.next = a ? a : b;
return dummy.next;
}
toArray(mergeTwoLists(buildList([1, 3, 5]), buildList([2, 4, 6])));Done
The first 9 calls, of 25. This one does not fit on a page.
More like this
All linked lists examples (9) →- Reverse a list Three pointers, one pass — flip every link as you walk.
- Detect a cycle A slow and a fast pointer must meet if the list loops.
- Middle node When the fast pointer finishes, the slow one is halfway.
- Remove nth from end Open an n-node gap between two pointers, then walk them together.
- Palindrome list A list can’t be read backwards — so copy it out, then close in.
- Merge k lists Merge lists in pairs, halving how many remain each round.