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
+ /**
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
+ // runtime: 1ms
13
+ // memory: 58.22MB
14
+
15
+ function mergeTwoLists ( list1 : ListNode | null , list2 : ListNode | null ) : ListNode | null {
16
+ // 1. if next exists
17
+ if ( ! list1 && ! list2 )
18
+ return null
19
+ else if ( ! list1 ) return list2
20
+ else if ( ! list2 ) return list1
21
+ // 2. compare value and link node
22
+ else if ( list1 . val <= list2 . val ) return new ListNode ( list1 . val , mergeTwoLists ( list1 . next , list2 ) )
23
+ else return new ListNode ( list2 . val , mergeTwoLists ( list1 , list2 . next ) )
24
+
25
+ } ;
You can’t perform that action at this time.
0 commit comments