21. Merge Two Sorted Lists
¶
- Time: $O(|\texttt{list1}| + |\texttt{list2}|))$
- Space: $O(1)$
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
var mergeTwoLists = function(l1, l2) {
const dummy = new ListNode();
let cur = dummy;
while (l1 && l2) {
if (l1.val < l2.val) { cur.next = l1; l1 = l1.next; }
else { cur.next = l2; l2 = l2.next; }
cur = cur.next;
}
cur.next = l1 || l2;
return dummy.next;
};