zoukankan      html  css  js  c++  java
  • Rotate List 面试题

    今天做了leetcode的Rotate List,刚开始头脑不清楚,写的乱七八糟的,后来改了下,提交了,能过,把代码贴出来。

    做题的时候头脑要清楚,我刚开始做完的时候才发现我把向左向右移动弄反了,后来修改了下。

     1 public static ListNode rotateRight(ListNode head, int n) {
     2         ListNode first=head;
     3         ListNode second=head;
     4         ListNode result=null;
     5         ListNode t=null;
     6         int ln=0;
     7         if(head==null)
     8             return result;
     9         while(head.next!=null){
    10             ln++;
    11             head=head.next;
    12         }
    13         ln++;//求出list长度
    14         n=n%ln;
    15         n=ln-n;//求出向右移动距离
    16         if(n==0)
    17             return first;
    18         
    19         while(n>1){
    20             if(first.next!=null)
    21                 first=first.next;
    22             else 
    23                 first=head;
    24             n--;
    25         }
    26         t=first;
    27         if(t.next==null)
    28             return second;
    29         else{
    30             result=first.next;
    31             t.next=null;
    32             first=result;
    33         }//将移动后的链表的尾巴确定        
    34         while(first.next!=null){
    35             first=first.next;
    36         }
    37         first.next=second;//将链表头与尾连起来
    38         return result;        
    39     }
  • 相关阅读:
    PDB文件详解
    C++模板常用功能讲解
    Windows下多线程编程(二)
    关于静态库中使用全局变量可能导致的问题
    js中的函数
    js中字符串的加密base64
    列表推导式
    函数和方法的区别
    xshell连不上虚拟机
    网络编程,并行,并发和协程
  • 原文地址:https://www.cnblogs.com/weilq/p/3622731.html
Copyright © 2011-2022 走看看