61-旋转链表

要点:

1、计算旋转的次数rot=k%len

2、链表尾部要链接头部构成循环条件,才能输出完整的循环链表

3、在头部放指针分别遍历一定次数,寻找到头尾,再将尾部链接下一个元素断开又形成了单链表。

 1 public ListNode rotateRight(ListNode head, int k) {
 2     if(head==null||k==0){
 3         return head;
 4     }
 5     ListNode cursor=head;
 6     ListNode tail=null;//尾指针
 7     int length=1;
 8     while(cursor.next!=null)//循环 得到总长度
 9     {
10         cursor=cursor.next;
11         length++;
12     }
13     int loop=length-(k%length);//得到循环的次数
14     tail=cursor;//指向尾结点
15     cursor.next=head;//改成循环链表
16     cursor=head;//指向头结点
17     for(int i=0;i<loop;i++){//开始循环
18         cursor=cursor.next;
19         tail=tail.next;
20     }
21     tail.next=null;//改成单链表
22     return cursor;//返回当前头
23 }
View Code

猜你喜欢

转载自www.cnblogs.com/nxnslc-blog/p/12448101.html
61-
今日推荐