我们首先计算出链表的长度 nnn,并找到该链表的末尾节点,将其与头节点相连。这样就得到了闭合为环的链表。然后我们找到新链表的最后一个节点(即原链表的第 (n−1)−(k mod n)(n - 1) - (k \bmod n)(n−1)−(kmodn) 个节点),将当前闭合为环的链表断开,即可得到我们所需要的结果。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(k == 0 || head == nullptr || head->next == nullptr) return head;
ListNode* cur = head;
int n = 1;
while(cur->next != nullptr){
cur = cur->next;
n++;
}
int add = n - k % n;
if(add == n) return head;
cur->next = head;
while(add--){
cur = cur->next;
}
ListNode* res = cur->next;
cur->next = nullptr;
return res;
}
};