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.
//#61 Rotate List
//12ms 90.07%
#include <iostream>
using namespace std;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k)
{
if(head == NULL || head->next == NULL) return head;
int size(0);
ListNode *t(head);
while(t->next != NULL)
{
size ++;
t = t->next;
}
size ++;
k = k % size;
if(k == 0) return head;
ListNode *p(head);
for(int i=0; i<size-k-1; i++)
{
p = p->next;
}
t->next = head;
head = p->next;
p->next = NULL;
return head;
}
};