Merge two sorted linked lists by reconnecting their existing nodes.
Use the editor below to combine two sorted linked lists.
Merge the existing nodes
Compare the current nodes and attach the smaller one to the merged tail. Either list may be empty, and equal or negative values may appear.
Submit your implementation when it passes the examples.
Given the heads of two sorted singly linked lists, combine their existing nodes into one sorted list.
Return the head of the merged list. Each node has the shape { val, next }.
0 ≤ total number of nodes ≤ 100Results appear here after a run.
A dummy node gives the merged list a stable starting point. Repeatedly connect the tail to the smaller current node and advance only that list.
When one list ends, attach the entire remaining chain with a single tail.next assignment. Return dummy.next. The dummy supplied a place for the first assignment and contributes no value to the result.
function mergeTwoLists(list1, list2) {
const dummy = { val: 0, next: null };
let tail = dummy;
let first = list1;
let second = list2;
while (first !== null && second !== null) {
if (first.val <= second.val) {
tail.next = first;
first = first.next;
} else {
tail.next = second;
second = second.next;
}
tail = tail.next;
}
tail.next = first ?? second;
return dummy.next;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n + m) | Lists of lengths n and m need at most n + m - 1 comparisons when both are nonempty. The final link attaches the remaining chain. |
| Auxiliary space | O(1) | Only a dummy node and a fixed number of references are added. |