-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.ts
58 lines (52 loc) · 1.29 KB
/
res.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
/**
* Definition for singly-linked list.
*/
// @ts-ignore
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 swapPairs(head: ListNode | null): ListNode | null {
if (!head?.next) {
return head;
}
const result = head.next;
let prevPoint = null;
let currentPoint: ListNode | null = head;
while (currentPoint) {
const nextPoint = currentPoint.next;
const restPoint = nextPoint?.next as ListNode | null;
if (nextPoint) {
currentPoint.next = restPoint;
nextPoint.next = currentPoint;
if (prevPoint) {
prevPoint.next = nextPoint;
}
prevPoint = currentPoint;
currentPoint = restPoint;
} else {
break;
}
}
return result;
};
/**
* 递归法
* @param head
*/
function swapPairs2(head: ListNode | null): ListNode | null {
if (!head?.next) {
return head;
}
const result = head.next;
head.next = swapPairs(result.next);
result.next = head;
return result;
}