File tree 1 file changed +13
-12
lines changed
scripts/algorithms/M/Merge Two Sorted Lists
1 file changed +13
-12
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 127 ms (Top 16.18%) | Memory: 43.7 MB (Top 91.75%)
1
2
/**
2
3
* Definition for singly-linked list.
3
4
* function ListNode(val, next) {
4
- * this.val = (val===undefined ? 0 : val)
5
- * this.next = (next===undefined ? null : next)
5
+ * this.val = (val===undefined ? 0 : val)
6
+ * this.next = (next===undefined ? null : next)
6
7
* }
7
8
*/
8
9
/**
11
12
* @return {ListNode }
12
13
*/
13
14
var mergeTwoLists = function ( list1 , list2 ) {
14
-
15
+
15
16
if ( ! list1 ) return list2
16
17
if ( ! list2 ) return list1
17
-
18
+
18
19
let mergedList = new ListNode ( 0 ) ;
19
20
let ptr = mergedList ;
20
21
let curr1 = list1 ;
21
22
let curr2 = list2 ;
22
-
23
+
23
24
while ( curr1 && curr2 ) {
24
-
25
+
25
26
let newNode = new ListNode ( ) ;
26
27
if ( ! curr2 || curr1 . val < curr2 . val ) {
27
28
newNode . val = curr1 . val ;
@@ -34,19 +35,19 @@ var mergeTwoLists = function(list1, list2) {
34
35
ptr . next = newNode
35
36
curr2 = curr2 . next ;
36
37
}
37
-
38
+
38
39
ptr = ptr . next
39
- }
40
-
40
+ }
41
+
41
42
if ( curr1 !== null ) {
42
43
ptr . next = curr1 ;
43
44
curr1 = curr1 . next ;
44
45
}
45
-
46
+
46
47
if ( curr2 !== null ) {
47
48
ptr . next = curr2 ;
48
49
curr2 = curr2 . next ;
49
50
}
50
-
51
+
51
52
return mergedList . next
52
- } ;
53
+ } ;
You can’t perform that action at this time.
0 commit comments