File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments