Description
Submission
/**
* 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 == nullptr) return nullptr;
if(k == 0) return head;
int len = 0;
ListNode *res, *endPtr;
for(ListNode* ptr = head; ptr != nullptr; ptr = ptr->next, len++){
endPtr = ptr;
}
k = k % len;
if(k == 0) return head;
ListNode* ptr = head;
for(int i = 0; i < len - k - 1; ++i, ptr = ptr->next);
res = ptr->next;
ptr->next = nullptr;
endPtr->next = head;
return res;
}
};
Submission 210327
/**
* 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) return nullptr;
int cnt = 0;
ListNode* tail = head;
for(; tail->next; tail = tail->next, cnt++);
cnt++;
k %= cnt;
if(k == 0 || !head->next) return head;
ListNode* node = head;
for(int i = 0; i < cnt - k - 1; ++i, node = node->next);
ListNode* ret = node->next;
node->next = nullptr;
tail->next = head;
return ret;
}
};