Merge Two Sorted Lists
Combine two already-sorted linked lists into a single sorted list.
Input Format
Implement mergeTwoLists(l1, l2). Inputs below show JavaScript function arguments; there is no stdin parsing.
Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement.
Returned list heads are displayed as value arrays; a null head is [].
Sample Input and Output
Example 1 ยท Run Sample
Input
l1 = [1,2,4]
l2 = [1,3,4] Output
[1,1,2,3,4,4] Example 2
Input
l1 = []
l2 = [] Output
[] Constraints
- 0 to 50 nodes per list
- -100 <= Node.val <= 100
Test Cases (2)
Case 1
Args: [[1,2,4],[1,3,4]]
Expected: [1,1,2,3,4,4]
Case 2
Args: [[],[]]
Expected: []
Topics
Iterative Merge
function mergeTwoLists(l1, l2) {
const dummy = {val: 0, next: null};
let curr = dummy;
while (l1 && l2) {
if (l1.val <= l2.val) { curr.next = l1; l1 = l1.next; }
else { curr.next = l2; l2 = l2.next; }
curr = curr.next;
}
curr.next = l1 || l2;
return dummy.next;
}Time: O(m + n) | Space: O(1)
Saved in this browser only. Private to you.