# C++实现LeetCode(61.旋转链表)

[LeetCode] 61. Rotate List 旋转链表 Given the head of a linked list, rotate the list to the right by k places.

## [LeetCode] 61. Rotate List 旋转链表

Given the head of a linked list, rotate the list to the right by k places.

Example 1:

Input: head = [1,2,3,4,5], k = 2

Output: [4,5,1,2,3]

Example 2:

Input: head = [0,1,2], k = 4

Output: [2,0,1]

Constraints:

• The number of nodes in the list is in the range [0, 500].
• -100 <= Node.val <= 100
• 0 <= k <= 2 * 109

解法一：

```class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
int n = 0;
while (cur) {
++n;
cur = cur->next;
}
k %= n;
for (int i = 0; i < k; ++i) {
if (fast) fast = fast->next;
}
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
fast = slow->next;
slow->next = NULL;
return fast;
}
};```

```class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
int n = 1;
while (cur->next) {
编程客栈        ++n;
cur = cur->next;
}
int m = n - k % n;
for (int i = 0; i < m; ++i) {
cur = cur-编程客栈>next;
}