Skip to content

Commit 2830df0

Browse files
committed
add: #224 Merge Two Sorted Lists
1 parent 301430f commit 2830df0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
const dummy = new ListNode();
15+
let current = dummy;
16+
17+
const addNode = (val: number) => {
18+
current.next = new ListNode(val);
19+
current = current.next;
20+
};
21+
22+
while (list1 !== null && list2 !== null) {
23+
if (list1.val < list2.val) {
24+
addNode(list1.val);
25+
list1 = list1.next;
26+
} else if (list1.val > list2.val) {
27+
addNode(list2.val);
28+
list2 = list2.next;
29+
} else {
30+
addNode(list1.val);
31+
addNode(list2.val);
32+
list1 = list1.next;
33+
list2 = list2.next;
34+
}
35+
}
36+
37+
current.next = list1 !== null ? list1 : list2;
38+
return dummy.next;
39+
};

0 commit comments

Comments
 (0)