Skip to content

Commit 563ba42

Browse files
add solution 021[js]
1 parent c6a91a9 commit 563ba42

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
const mergeTwoLists2 = function (l1, l2) {
2+
if (l1 === null && l2 === null) {
3+
return null;
4+
}
5+
if (l1 !== null && l2 === null) {
6+
return l1;
7+
}
8+
if (l1 === null && l2 !== null) {
9+
return l2;
10+
}
11+
if (l1 !== null && l2 !== null) {
12+
let t = null, h = null;
13+
if (l1.val > l2.val) {
14+
t = l2;
15+
h = l2;
16+
l2 = l2.next;
17+
} else {
18+
t = l1;
19+
h = l1;
20+
l1 = l1.next;
21+
}
22+
while (l1 !== null && l2 !== null) {
23+
if (l1.val > l2.val) {
24+
t.next = l2;
25+
t = t.next;
26+
l2 = l2.next;
27+
} else {
28+
t.next = l1;
29+
t = t.next;
30+
l1 = l1.next;
31+
}
32+
}
33+
while (l1 !== null) {
34+
t.next = l1;
35+
l1 = l1.next;
36+
t = t.next;
37+
}
38+
while (l2 !== null) {
39+
t.next = l2;
40+
l2 = l2.next;
41+
t = t.next;
42+
}
43+
return h;
44+
}
45+
}
46+
47+
const mergeTwoLists = function (l1, l2) {
48+
if (l1 === null) return l2;
49+
if (l2 === null) return l1;
50+
if (l1.val < l2.val) {
51+
l1.next = mergeTwoLists(l1.next, l2);
52+
return l1;
53+
} else {
54+
l2.next = mergeTwoLists(l1, l2.next);
55+
return l2;
56+
}
57+
}

0 commit comments

Comments
 (0)