Skip to content

Commit c2b59a4

Browse files
committed
solve: 21. Merge Two Sorted Lists
1 parent 3734e6a commit c2b59a4

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

merge-two-sorted-lists/evan.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
function ListNode(val, next) {
2+
this.val = val === undefined ? 0 : val;
3+
this.next = next === undefined ? null : next;
4+
}
5+
6+
/**
7+
* @param {ListNode} list1
8+
* @param {ListNode} list2
9+
* @return {ListNode}
10+
*/
11+
var mergeTwoLists = function (list1, list2) {
12+
if (!list1 && !list2) {
13+
return null;
14+
}
15+
16+
if (!list1 || !list2) {
17+
return [list1, list2].find(Boolean);
18+
}
19+
20+
// firstPointer is a head of list who has the smallest value of node
21+
let [firstPointer, secondPointer] =
22+
list1.val < list2.val ? [list1, list2] : [list2, list1];
23+
const mergedList = firstPointer;
24+
25+
if (firstPointer.next === null) {
26+
firstPointer.next = secondPointer;
27+
return mergedList;
28+
}
29+
30+
while (secondPointer !== null) {
31+
let nextFirstPointer = firstPointer.next;
32+
const nextSecondPointer = secondPointer.next;
33+
34+
while (
35+
firstPointer.next !== null &&
36+
firstPointer.next.val < secondPointer?.val
37+
) {
38+
firstPointer = firstPointer.next;
39+
nextFirstPointer = firstPointer.next;
40+
}
41+
42+
firstPointer.next = secondPointer;
43+
firstPointer.next.next = nextFirstPointer;
44+
45+
secondPointer = nextSecondPointer;
46+
firstPointer = firstPointer.next;
47+
}
48+
49+
return mergedList;
50+
};

0 commit comments

Comments
 (0)