一、题目要求
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
.
二、代码实现
ListNode* rotateRight(ListNode* head, int k) {
ListNode* start=head,*p;
int len=0;
if(head==NULL||head->next==NULL)
return head;
while(start!=NULL)
{
start=start->next;
len++;
}
k=k%len;
if(!k)
return head;
//
start=head;
p=head;
while(k--)
start=start->next;
while(start->next!=NULL)
{
start=start->next;
p=p->next;
}
start->next=head;
head=p->next;
p->next=NULL;
return head;
}