Skip to content

Commit 9fac6a2

Browse files
committed
week4: merge-two-sorted-lists
1 parent 0f596fb commit 9fac6a2

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

merge-two-sorted-lists/reeseo3o.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 1. Recursive approach
3+
* Time complexity: O(n + m)
4+
* Space complexity: O(n + m)
5+
*/
6+
// const mergeTwoLists = (list1, list2) => {
7+
// if (!list1) return list2;
8+
// if (!list2) return list1;
9+
//
10+
// if (list1.val <= list2.val) {
11+
// list1.next = mergeTwoLists(list1.next, list2);
12+
// return list1;
13+
// } else {
14+
// list2.next = mergeTwoLists(list1, list2.next);
15+
// return list2;
16+
// }
17+
// };
18+
19+
/**
20+
* 2. Iterative approach + Dummy Node
21+
* Time complexity: O(n + m)
22+
* Space complexity: O(1)
23+
*/
24+
const mergeTwoLists = (list1, list2) => {
25+
const dummy = new ListNode(-1);
26+
let current = dummy;
27+
28+
while (list1 !== null && list2 !== null) {
29+
if (list1.val <= list2.val) {
30+
current.next = list1;
31+
list1 = list1.next;
32+
} else {
33+
current.next = list2;
34+
list2 = list2.next;
35+
}
36+
current = current.next;
37+
}
38+
39+
current.next = list1 ?? list2;
40+
41+
return dummy.next;
42+
};

0 commit comments

Comments
 (0)