[Leetcode] Rotate List

来源:互联网 发布:linux上telnet 编辑:程序博客网 时间:2024/06/15 04:53
题目:循环单链表。

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;}


0 0
原创粉丝点击