/**
* 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(!head || !k){
return head;
}
ListNode* tail;
int n = 1;
for(ListNode*p = head; p; p = p->next){
n++;
tail = p;
}
k = k % n;
ListNode* p2 = head;
for(int i = 0; i < n - k -2; i++){
p2 = p2->next;
}
tail->next = head;//尾结点指向头结点
head = p2->next;
p2->next = nullptr;//n-k个节点处断开
return head;
}
};