# 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 * 10^9`

``````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;
}
cur->next = NULL;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/61

Rotate Array

https://leetcode.com/problems/rotate-list/

https://leetcode.com/problems/rotate-list/discuss/22715/Share-my-java-solution-with-explanation

https://leetcode.com/problems/rotate-list/discuss/22735/My-clean-C%2B%2B-code-quite-standard-(find-tail-and-reconnect-the-list)

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation