Skip to content

Commit bde7c97

Browse files
committed
merge two sorted lists solution
1 parent 7b30acd commit bde7c97

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

merge-two-sorted-lists/hyer0705.ts

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
14+
if (!list1 && !list2) return null;
15+
16+
if (!list1) return list2;
17+
if (!list2) return list1;
18+
19+
const dummyHead = new ListNode(-101);
20+
let tail = dummyHead;
21+
22+
let pointerOne: ListNode | null = list1;
23+
let pointerTwo: ListNode | null = list2;
24+
25+
while (pointerOne && pointerTwo) {
26+
if (pointerOne.val <= pointerTwo.val) {
27+
tail.next = pointerOne;
28+
pointerOne = pointerOne.next;
29+
} else {
30+
tail.next = pointerTwo;
31+
pointerTwo = pointerTwo.next;
32+
}
33+
34+
tail = tail.next;
35+
}
36+
37+
if (pointerOne) {
38+
tail.next = pointerOne;
39+
} else {
40+
tail.next = pointerTwo;
41+
}
42+
43+
return dummyHead.next;
44+
}

0 commit comments

Comments
 (0)