Skip to content

Commit 53b0e80

Browse files
committed
Merge Two Sorted Lists solution
1 parent 47e2958 commit 53b0e80

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

20-mergeTwoSortedLists.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} l1
10+
* @param {ListNode} l2
11+
* @return {ListNode}
12+
*/
13+
var mergeTwoLists = function (l1, l2) {
14+
if (l1 === null && l2 === null) {
15+
return null;
16+
} else if (l1 === null) {
17+
return l2;
18+
} else if (l2 === null) {
19+
return l1;
20+
}
21+
let arr = [];
22+
let i = l1;
23+
let j = l2;
24+
while (true) {
25+
if (i.val < j.val) {
26+
arr.push(i);
27+
i = i.next;
28+
} else {
29+
arr.push(j);
30+
j = j.next;
31+
}
32+
33+
if (i === null) {
34+
arr.push(j);
35+
break;
36+
} else if (j === null) {
37+
arr.push(i);
38+
break;
39+
}
40+
}
41+
42+
for (let i = 0; i < arr.length - 1; i++) {
43+
arr[i].next = arr[i + 1];
44+
}
45+
46+
return arr[0];
47+
};
48+
49+
function ListNode(val, next) {
50+
this.val = val === undefined ? 0 : val;
51+
this.next = next === undefined ? null : next;
52+
}
53+
54+
r = new ListNode(122);
55+
c = new ListNode(21, r);
56+
b = new ListNode(19, c);
57+
a = new ListNode(17, b);
58+
59+
f = new ListNode(20);
60+
e = new ListNode(18, f);
61+
d = new ListNode(16, e);
62+
63+
console.log(mergeTwoLists(a, d));

0 commit comments

Comments
 (0)