给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

思路

  1. 遍历链表,获取尾部节点和链表长度 length
  2. k = length - (k % length),向右移动 k 相当于向左移动 length - k
  3. k === length 则不作任何操作
  4. 找到第 k 个节点,分割链表并重新拼接
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
var rotateRight = function (head, k) {
if (!head) {
return null
}
let cur = head
let length = 0
let tail = null
while (cur) {
++length
tail = cur
cur = cur.next
}
k = length - (k % length)
if (k === length) {
return head
}
let kNode = head
for (let i = 1; i < k; ++i) {
kNode = kNode.next
}
const newHead = kNode.next
kNode.next = null
tail.next = head
return newHead
}