-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmergeList.js
More file actions
56 lines (46 loc) · 767 Bytes
/
mergeList.js
File metadata and controls
56 lines (46 loc) · 767 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { ListNode } from './linkedList';
/**
* 合并两个链表
*/
export function mergeList(l1, l2) {
if (!l1) {
return l2;
}
if (!l2) {
return l1;
}
if (l1.val < l2.val) {
l1.next = mergeList(l1.next, l2);
return l1;
}
l2.next = mergeList(l1, l2.next);
return l2;
}
export function mergeListNR(l1, l2) {
if (!l1) {
return l2;
}
if (!l2) {
return l1;
}
const root = new ListNode();
let current = root;
while (l1 && l2) {
if (l1.val < l2.val) {
current.next = l1;
l1 = l1.next;
}
else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
if (l1) {
current.next = l1;
}
else if (l2) {
current.next = l2;
}
return root.next;
}