Skip to content

Commit 1c7ba0a

Browse files
authored
solution on merge-two-sorted-lists
1 parent 2fd52b4 commit 1c7ba0a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

merge-two-sorted-lists/Lustellz.ts

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

0 commit comments

Comments
 (0)