C语言版本
题目:
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
.
主要注意两点:
1.指针未声明,不能引用。
2.K只是一个非负数,可能大于链表长度n。
代码如下:
struct ListNode* rotateRight(struct ListNode* head, int k) {
struct ListNode* p=head,*p1=head,*p2=NULL,*p3=NULL;
int i;
if(!p)return head;
int n=0;
while(p){p=p->next;n++;}
k=k%n;
//printf("%d\n",k);
if(k!=0)
{ p=head;
for(i=0;i<k;i++)
p=p->next;
while(p)
{p3=p1;p1=p1->next;p2=p;p=p->next;}
if(p2&&p3)
{
p2->next=head;
p3->next=NULL;
}
head=p1;
}
return head;
}