-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
48 lines (47 loc) · 945 Bytes
/
solution.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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var rotateRight = function (head, k) {
if (head === null || head.next === null) {
return head;
}
// 先找出总数来
let count = 0;
let node = head;
let prev;
while (node !== null) {
count++;
prev = node;
node = node.next;
}
// 处理rotate多轮的情况
k = k % count;
if (k === 0) {
return head;
}
// 利用快慢指针找到倒数第k的节点
let slow = head;
let fast = head;
while (k > 0) {
k--;
fast = fast.next;
}
while (fast.next !== null) {
slow = slow.next;
fast = fast.next;
}
// rotate
node = slow.next;
slow.next = null;
prev.next = head;
return node;
};