Skip to content

Commit 27d8ec8

Browse files
committed
合并链表代码
1 parent f72d0bf commit 27d8ec8

File tree

1 file changed

+93
-1
lines changed

1 file changed

+93
-1
lines changed

main.js

Lines changed: 93 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,93 @@
1-
console.log("222")
1+
function ListNode(val) {
2+
this.val = val;
3+
this.next = null;
4+
}
5+
6+
const a = new ListNode(1)
7+
const b = new ListNode(2)
8+
const c = new ListNode(4)
9+
a.next = b
10+
b.next = c
11+
const d = new ListNode(1)
12+
const e = new ListNode(3)
13+
const f = new ListNode(4)
14+
d.next = e
15+
e.next = f
16+
17+
function bianli(root, vals = []) {
18+
while (root && root !== null) {
19+
vals.push(root.val)
20+
root = root.next
21+
}
22+
return vals
23+
}
24+
// bianli(a)
25+
// bianli(d)
26+
27+
/** 迭代法
28+
* @param {ListNode} l1
29+
* @param {ListNode} l2
30+
* @return {ListNode}
31+
*/
32+
var mergeTwoLists = function (l1, l2) {
33+
let res = new ListNode();
34+
let root = res
35+
while (l1 !== null && l2 !== null) {
36+
if (l1.val <= l2.val) {
37+
root.next = l1;
38+
l1 = l1.next;
39+
} else {
40+
root.next = l2
41+
l2 = l2.next;
42+
}
43+
root = root.next
44+
}
45+
if (l1 != null) {
46+
root.next = l1;
47+
}
48+
49+
if (l2 != null) {
50+
root.next = l2;
51+
}
52+
return res.next
53+
};
54+
55+
/**转化数组法
56+
* @param {ListNode} l1
57+
* @param {ListNode} l2
58+
* @return {ListNode}
59+
*/
60+
var mergeTwoLists2 = function (l1, l2) {
61+
if (l1 == null && l2 == null) return l1
62+
const l1res = bianli(l1)
63+
const l2res = bianli(l2)
64+
const resData = [...l1res, ...l2res].sort((a, b) => a - b)
65+
let root = new ListNode(resData[0]);
66+
let res = root;
67+
for (let i = 1; i < resData.length; i++) {
68+
res.next = new ListNode(resData[i])
69+
res = res.next;
70+
}
71+
return root
72+
};
73+
74+
75+
/**递归
76+
* @param {ListNode} l1
77+
* @param {ListNode} l2
78+
* @return {ListNode}
79+
*/
80+
var mergeTwoLists3 = function (l1, l2) {
81+
if (l1 == null) {
82+
return l2;
83+
} else if (l2 == null) {
84+
return l1;
85+
} else if (l1.val < l2.val) {
86+
l1.next = mergeTwoLists(l1.next, l2);
87+
return l1;
88+
} else {
89+
l2.next = mergeTwoLists(l1, l2.next);
90+
return l2;
91+
}
92+
};
93+
console.log(bianli(mergeTwoLists3(a, d)))

0 commit comments

Comments
 (0)