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