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->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 *rotateRight(ListNode *head, int k)
{
if(NULL == head || k == 0)
return head;
ListNode *Head = new ListNode (-1);
ListNode * cur = Head, *fast = Head, *tmp = head;
int length = 0;
Head->next = head;
while(NULL != tmp)
{
tmp = tmp->next;
length ++;
}
k = k%length;//k比链表长度还大
if(k == 0)
return head;
for (int i=0;i<k;i++)
fast = fast->next;
while(fast->next != NULL)
{
cur = cur->next;
fast = fast->next;
}
fast->next = Head->next;
Head->next = cur->next;
cur->next = NULL;
return Head->next;
}
};
测试
#include"head.h"
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k)
{
if(NULL == head || k == 0)
return head;
ListNode *Head = new ListNode (-1);
ListNode * cur = Head, *fast = Head, *tmp = head;
int length = 0;
Head->next = head;
while(NULL != tmp)
{
tmp = tmp->next;
length ++;
}
k = k%length;
if(k == 0)
return head;
for (int i=0;i<k;i++)
fast = fast->next;
while(fast->next != NULL)
{
cur = cur->next;
fast = fast->next;
}
fast->next = Head->next;
Head->next = cur->next;
cur->next = NULL;
return Head->next;
}
};
int main()
{
int A[] = {1,2,3,4,5};
vector<int> vec(A, A+5);
ListNode *head = makelist(vec);
printlist(head);
Solution s;
ListNode * p = s.rotateRight(head, 5);
printlist(p);
}