File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 1+ var mergeTwoLists = function ( list1 , list2 ) {
2+ // create a placeholder node and use it as a starting point
3+ let placeholder = { val : - 1 , next : null } ;
4+ let current = placeholder ;
5+
6+ // loop through the lists until one of them is fully traversed
7+ while ( list1 !== null && list2 !== null ) {
8+ if ( list1 . val <= list2 . val ) {
9+ // connect the element of list1 with the current node
10+ current . next = list1 ;
11+ // move list1 to its next node
12+ list1 = list1 . next ;
13+ } else {
14+ current . next = list2 ;
15+ list2 = list2 . next ;
16+ }
17+ // move the current pointer to the newly added node
18+ current = current . next ;
19+ }
20+ current . next = list1 !== null ? list1 : list2 ;
21+ return placeholder . next ;
22+ } ;
23+
24+ // Time Complexity: O(n+m);
25+ // Space Complexity: O(1)
You can’t perform that action at this time.
0 commit comments