21. Merge Two Sorted Lists
Last updated
Last updated
time: O(n + m)
space: O(n + m)
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
const dummy = new ListNode();
var mergeTwoLists = function(list1, list2) {
dummy.next = null;
let prev = dummy;
// // do not need
// let curr1 = list1;
// let curr2 = list2;
while (list1 !== null && list2 !== null) {
if (list1.val <= list2.val) {
prev.next = list1;
prev = list1;
list1 = list1.next;
} else {
prev.next = list2;
prev = list2;
list2 = list2.next;
}
}
if (list1 !== null) {
prev.next = list1;
}
if (list2 !== null) {
prev.next = list2;
}
return dummy.next;
};
do not need iteration
// as is
while (curr1 !== null) {
prev.next = curr1;
prev = curr1;
curr1 = curr1.next;
}
while (curr2 !== null) {
prev.next = curr2;
prev = curr2;
curr2 = curr2.next;
}
// to be
if (curr1 !== null) {
prev.next = curr1;
}
if (curr2 !== null) {
prev.next = curr2;
}