Skip to content

Commit 70307dc

Browse files
committed
solve: W04 merge two sorted list
1 parent 60c4a8b commit 70307dc

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
};

0 commit comments

Comments
 (0)