-
Notifications
You must be signed in to change notification settings - Fork 0
/
19-剑指 Offer 25. 合并两个排序的链表.ts
78 lines (68 loc) · 1.62 KB
/
19-剑指 Offer 25. 合并两个排序的链表.ts
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
export class ListNode {
val: number
next: ListNode | null
constructor(val?: number, next?: ListNode | null) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
}
function mergeTwoLists(l1: ListNode | null, l2: ListNode | null): ListNode | null {
if (!l1 && !l2) return null;
if (!l1) return l2;
if (!l2) return l1;
let start: ListNode | null = null;
let tail: ListNode | null = null;
while (l1 && l2) {
let newNode: ListNode | null = null
if (l1.val <= l2.val) {
newNode = new ListNode(l1.val);
l1 = l1.next;
} else {
newNode = new ListNode(l2.val);
l2 = l2.next;
}
if (!start) {
start = newNode;
tail = newNode;
} else {
tail!.next = newNode;
tail = tail!.next
}
}
while (l1) {
tail!.next = new ListNode(l1.val);
tail = tail!.next
l1 = l1.next
}
while (l2) {
tail!.next = new ListNode(l2.val);
tail = tail!.next
l2 = l2.next
}
return start;
};
function mergeTwoLists1(l1: ListNode | null, l2: ListNode | null): ListNode | null {
// 判断边界
if (!l1 && !l2) return null;
if (!l1) return l2;
if (!l2) return l1;
// 头部
let head = l1.val <= l2.val ? l1 : l2;
// 比较指针
let cur1: ListNode | null = head.next;
let cur2: ListNode | null = head === l1 ? l2 : l1;
// 辅助递增指针
let tail = head;
while (cur1 && cur2) {
if (cur1.val <= cur2.val) {
tail.next = cur1;
cur1 = cur1.next
} else {
tail.next = cur2;
cur2 = cur2.next
}
tail = tail.next
}
tail.next = cur1 || cur2;
return head;
};