-
Notifications
You must be signed in to change notification settings - Fork 0
/
24.两两交换链表中的节点.js
52 lines (48 loc) · 1.07 KB
/
24.两两交换链表中的节点.js
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
/*
* @lc app=leetcode.cn id=24 lang=javascript
*
* [24] 两两交换链表中的节点
*/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function (head) {
const reverseN = (head, k) => {
let p = head;
const cnt = k;
// 判断当前节点够不够k个节点
while (--k && p) p = p.next;
if (!p) return head;
return __reverseN(head, cnt);
};
const __reverseN = (head, k) => {
if (k === 1) return head;
// 翻转后的尾节点
let tail = head.next;
// 翻转后的头结点
let p = __reverseN(head.next, k - 1);
head.next = tail.next;
tail.next = head;
return p;
};
if (!head || !head.next) return head;
const k = 2;
let res = new ListNode(0, head);
let p = res;
let q = p.next;
while ((p.next = reverseN(q, k))) {
p = q;
q = q.next;
}
return res.next;
};
// @lc code=end