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
.
我的C++代码!
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
int Length(ListNode *head)
{
int count=0;
ListNode *p;
p=head;
while(p)
{
count++;
p=p->next;
}
return count;
}
ListNode* rotateRight(ListNode* head, int k)
{
int len=Length(head);
if(head==NULL)
return head;
if(k>len)
k=k%len;
if(k==0||len==1||len==k)
return head;
int diff=len-k;
ListNode *p=head;
while(diff!=1)
{
p=p->next;
diff--;
}
ListNode *head1=p->next;
p->next=NULL;
ListNode *q=head1;
while(q->next)
q=q->next;
q->next=head;
return head1;
}