Loading

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

 

对于链表格式

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
现在设置一个无指向指针 Listnode *temp;
  设置一个空指针    Listnode *temp=NULL;
       设置一个有内容的指针  Listnode *temp=new Listnode(0);(指针的指向内容是0)
       值得注意的是,我们将指针初始化内容后才可以使用temp->next,前两种方式并不能直接使用next指向!读者可能觉得很简单,但是写代码的时候就很难发现错误。所以一定要注意一下
posted @ 2020-03-09 12:44  是凉城吖  阅读(127)  评论(0编辑  收藏  举报