Skip to content

Commit a2f3b3e

Browse files
committed
feat: merge two sorted lists
1 parent f522fdb commit a2f3b3e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

merge-two-sorted-lists/soobing3.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
class ListNode {
3+
val: number
4+
next: ListNode | null
5+
constructor(val?: number, next?: ListNode | null) {
6+
this.val = (val===undefined ? 0 : val)
7+
this.next = (next===undefined ? null : next)
8+
}
9+
}
10+
11+
12+
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
13+
let mergedList = new ListNode(0, null);
14+
const result = mergedList;
15+
16+
while(list1 && list2) {
17+
if(list1.val < list2.val) {
18+
mergedList.next = list1;
19+
list1 = list1.next;
20+
} else {
21+
mergedList.next = list2;
22+
list2 = list2.next;
23+
}
24+
mergedList = mergedList.next;
25+
}
26+
27+
mergedList.next = list1 ?? list2;
28+
29+
return result.next;
30+
};

0 commit comments

Comments
 (0)