Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverse(ListNode *head)
{
if(!head || !head->next)
return head;
ListNode *nextH = head->next;
ListNode *newH = reverse(nextH);
nextH->next = head;
head->next = NULL;
return newH;
}
ListNode *rotateRight(ListNode *head, int k)
{
if(!head || k == 0)
return head;
int n = 0;
ListNode *p = head;
ListNode *last = head;
while(p)
{
n++;
last = p;
p = p->next;
}
k = k % n;
if(k == 0)
return head;
n = n - k;
int i = 1;
p = head;
while(p && i<n)
{
i++;
p = p->next;
}
ListNode *next = p->next;
p->next = NULL;
last->next = head;
return next;
}
};