题目:循环单链表。
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
.
思路很简单,找到分割点,将分割点之后的链表变成新链表的前半部分,分割点之前的变为新链表后半部分,注意k可能很大,实际移动的k=k%length,具体过程在程序中注释。
ListNode *rotateRight(ListNode *head, int k)
{
if(head ==NULL || k==0) return head;
ListNode *x=head;
int i=1;
for(i=1; x ->next !=NULL; i++) //计算链表长度
x=x->next ;
ListNode *last=x; //保存最末尾节点
k=i-k%i; //分割点位置
if(k == i) return head; //等于原长不需移动
x=head;
for(; k<i&& k>1; k--) //找到分割点
x=x->next;
last->next=head; //最尾节点链接头结点
head=x->next; //下一个点为新头结点
x->next=NULL; //截断当前点
return head;
}