File tree 1 file changed +44
-0
lines changed
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/merge-two-sorted-lists
3
+ * time complexity : O(n)
4
+ * space complexity : O(1)
5
+ */
6
+
7
+ class ListNode {
8
+ val : number
9
+ next : ListNode | null
10
+ constructor ( val ?: number , next ?: ListNode | null ) {
11
+ this . val = ( val === undefined ? 0 : val )
12
+ this . next = ( next === undefined ? null : next )
13
+ }
14
+ }
15
+
16
+ function mergeTwoLists ( list1 : ListNode | null , list2 : ListNode | null ) : ListNode | null {
17
+ if ( ! list1 && ! list2 ) return null ;
18
+ if ( ! list1 ) return list2 ;
19
+ if ( ! list2 ) return list1 ;
20
+
21
+ const dummy = new ListNode ( ) ;
22
+ let current = dummy ;
23
+
24
+ while ( list1 && list2 ) {
25
+ if ( list1 . val < list2 . val ) {
26
+ current . next = list1 ;
27
+ list1 = list1 . next ;
28
+ } else {
29
+ current . next = list2 ;
30
+ list2 = list2 . next ;
31
+ }
32
+ current = current . next ;
33
+ }
34
+
35
+ current . next = list1 || list2 ;
36
+
37
+ return dummy . next ;
38
+ } ;
39
+
40
+ const input1 = new ListNode ( 1 , new ListNode ( 2 , new ListNode ( 4 ) ) ) ;
41
+ const input2 = new ListNode ( 1 , new ListNode ( 3 , new ListNode ( 4 ) ) ) ;
42
+
43
+ console . log ( 'output1:' , mergeTwoLists ( input1 , input2 ) ) ;
44
+ console . log ( 'output2:' , mergeTwoLists ( input2 , input1 ) ) ;
You can’t perform that action at this time.
0 commit comments