Given a list, rotate the list to the right by k places, where k is non-negative.
Example
Given 1->2->3->4->5->null and k=2
return 4->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:
/**
* @param head: the list
* @param k: rotate to the right k places
* @return: the list after rotation
*/
int ListCount(ListNode* head)
{
if (!head)
return 0;
int count = 1;
ListNode *pCurNode = head;
while (pCurNode->next)
{
pCurNode = pCurNode->next;
count++;
}
return count;
}
ListNode *rotateRight(ListNode *head, int k) {
// write your code here
if (!head)
return NULL;
if (k == 0)
return head;
int nodeCount = ListCount(head);
if (nodeCount == 1)
return head;
ListNode* pFastNode = head;
ListNode* pSlowNode = head;
ListNode fakeHead = ListNode(-1);
ListNode* pPreNode = &fakeHead;
pPreNode->next = head;
k = k%ListCount(head);
for (int i=1; i<=k-1; i++)
{
if (pFastNode->next)
{
pFastNode = pFastNode->next;
}
else
{
return head;
}
}
while (pFastNode->next != NULL)
{
pFastNode = pFastNode->next;
pSlowNode = pSlowNode->next;
pPreNode = pPreNode->next;
}
pFastNode->next = head;
pPreNode->next = NULL;
return pSlowNode;
}
};