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
.
class Solution{
public:
ListNode *rotateRight(ListNode *head, int k) {
if(head==NULL) return NULL;
int length = 0;
ListNode *current = head;
while(current)
{
current = current->next;
length ++;
}
k %= length;
if(k==0) return head;
ListNode *vHead = new ListNode(-1);
vHead->next = head;
int count = 0;
current = head;
ListNode *newTail = vHead;
while(count<length-k)
{
current = current->next;
newTail = newTail->next;
count++;
}
vHead->next = current;
newTail->next = NULL;
while(current->next)
{
current=current->next;
}
current->next = head;
return vHead->next;
}
};