Skip to content

Commit 5c0a937

Browse files
committed
Feat: 21. Merge Two Sorted Lists
1 parent ec10a0d commit 5c0a937

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

merge-two-sorted-lists/HC-kang.ts

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

0 commit comments

Comments
 (0)