File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-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
+ *
14
+ * Time Complexity: O(n + m)
15
+ * Space Complexity: O(n + m)
16
+ */
17
+ function mergeTwoLists ( list1 : ListNode | null , list2 : ListNode | null ) : ListNode | null {
18
+ if ( ! list1 && ! list2 ) {
19
+ // both lists are empty
20
+ return null
21
+ } else if ( ! list1 ) {
22
+ // list1 is empty
23
+ return list2
24
+ } else if ( ! list2 ) {
25
+ // list2 is empty
26
+ return list1
27
+ } else if ( list1 . val <= list2 . val ) {
28
+ // list1's current node is smaller
29
+ return new ListNode ( list1 . val , mergeTwoLists ( list1 . next , list2 ) )
30
+ } else {
31
+ // list2's current node is smaller
32
+ return new ListNode ( list2 . val , mergeTwoLists ( list1 , list2 . next ) )
33
+ }
34
+ } ;
You can’t perform that action at this time.
0 commit comments