题目描述:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *ret;
ListNode *rotateRight(ListNode *head, int k) {
if (!head)
return head;
ret = head;
while (k > 0){
int r = 0;
ListNode *last = rotate(ret, k, r);
if (r <= k)
last->next = NULL;
k -= r;
}
return ret;
}
ListNode *rotate(ListNode *node, int k, int &r){
if (!node)
return NULL;
ListNode *last = rotate(node->next, k, r);
if (r == k)
node->next = NULL;
if (r < k){
node->next = ret;
ret = node;
}
r++;
if (last)
return last;
else
return node;
}
};