File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * class ListNode {
4
+ * val: number
5
+ * next: ListNode | null
6
+ * constructor(val?: number, next?: ListNode | null) {
7
+ * this.val = (val===undefined ? 0 : val)
8
+ * this.next = (next===undefined ? null : next)
9
+ * }
10
+ * }
11
+ */
12
+
13
+ function mergeTwoLists ( list1 : ListNode | null , list2 : ListNode | null ) : ListNode | null {
14
+ if ( ! list1 && ! list2 ) return null ;
15
+
16
+ if ( ! list1 ) return list2 ;
17
+ if ( ! list2 ) return list1 ;
18
+
19
+ const dummyHead = new ListNode ( - 101 ) ;
20
+ let tail = dummyHead ;
21
+
22
+ let pointerOne : ListNode | null = list1 ;
23
+ let pointerTwo : ListNode | null = list2 ;
24
+
25
+ while ( pointerOne && pointerTwo ) {
26
+ if ( pointerOne . val <= pointerTwo . val ) {
27
+ tail . next = pointerOne ;
28
+ pointerOne = pointerOne . next ;
29
+ } else {
30
+ tail . next = pointerTwo ;
31
+ pointerTwo = pointerTwo . next ;
32
+ }
33
+
34
+ tail = tail . next ;
35
+ }
36
+
37
+ if ( pointerOne ) {
38
+ tail . next = pointerOne ;
39
+ } else {
40
+ tail . next = pointerTwo ;
41
+ }
42
+
43
+ return dummyHead . next ;
44
+ }
You can’t perform that action at this time.
0 commit comments