旋转链表
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
示例:
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
1
2
2
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var rotateRight = function(head, k) {
if(head === null || k === 0) return head
let size = 0
let list = head
// 先获取链表长度,其实向右移动k个位置,如果k小于链表长度,那就相当于是把从尾部开始k个节点放到头部
// 如果k大于链表长度,那就是取余,然后同理,把从尾部开始余数个节点放到头部
while (list) {
size++
list = list.next
}
let i = k % size
if(i === 0) return head
let cur = head
let j = 1
while (j < size - i) {
cur = cur.next
j++
}
// 获取到后面要放到头部的节点
let next = cur.next
cur.next = null
let prev = head
// 将前面节点拼接到后方(旋转)
let tail = next
while (tail && tail.next) {
tail = tail.next
}
tail.next = prev
return next
};
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
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
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/rotate-list/