/**
* 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) {
ListNode* pst = head;
ListNode* last = NULL;
int cnt = 0;
while(pst != NULL){
++cnt;
last = pst;
pst = pst -> next;
}
if(cnt == 0){
return head;
}
int actual = k % cnt;
last -> next = head;
pst = head;
for(int i = 0; i < cnt - actual - 1 ; ++i){
pst = pst -> next;
}
head = pst -> next;
pst->next = NULL;
return head;
}
};
|