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

 

示例 1:

LeetCode刷题笔记 61. 旋转链表_取模

 

 


输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
示例 2:

LeetCode刷题笔记 61. 旋转链表_取模_02

 

 


输入:head = [0,1,2], k = 4
输出:[2,0,1]
 

提示:

链表中节点的数目在范围 [0, 500] 内
-100 <= Node.val <= 100
0 <= k <= 2 * 109

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-list

思路:链表旋转->环形链表->%取模

新链表的尾部应该是 (n - k % n ) - 1 

代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode() : val(0), next(nullptr) {}
 7  *     ListNode(int x) : val(x), next(nullptr) {}
 8  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 9  * };
10  */
11 class Solution {
12 public:
13     ListNode* rotateRight(ListNode* head, int k) {
14         if (k == 0 || !head || !head->next) 
15             return head;
16         int n = 0;
17         ListNode* pTail = head, *pNewTail = head;
18         
19         while (pTail->next) {
20             ++n;
21             pTail = pTail->next;
22         }
23         ++n;
24         //求新链表头的位置
25         int mov = n - (k % n);
26 
27         if (mov == n) {
28             return head;
29         } 
30         pTail->next = head;//若不是旋转n的整数倍,环状链表
31 
32         while (--mov) {//新链表尾应为mov-1
33             pNewTail = pNewTail->next;
34         }
35         //解环
36         head = pNewTail->next;
37         pNewTail->next = nullptr;
38         
39         return head;
40     }
41 };