zoukankan      html  css  js  c++  java
  • 61. Rotate List

        /*
         * 61. Rotate List 
         * 2016-5-8 By Mingyang
         * 这种rotation的一定要记得模
         * 第一个代码少用了一个for循环,利用全局变量i的遍历,记录整个长度
         * 注意还是记得要模
         */
        public ListNode rotateRight(ListNode head, int n) {
            if (head==null||head.next==null) return head;
            ListNode dummy=new ListNode(0);
            dummy.next=head;
            ListNode fast=dummy,slow=dummy;
            int i;
            for (i=0;fast.next!=null;i++)//Get the total length 
                fast=fast.next;
            for (int j=i-n%i;j>0;j--) //Get the i-n%i th node
                slow=slow.next;
            fast.next=dummy.next; //Do the rotation
            dummy.next=slow.next;
            slow.next=null;
            return dummy.next;
        }
        //下面就是我的代码,没有这么简洁,但是可读性更强
        public ListNode rotateRight1(ListNode head, int k) {
            if(head==null)
              return head;
            ListNode prev=new ListNode(-1);
            ListNode run=head;
            int count=0;
            while(run!=null){
                run=run.next;
                count++;
            }
            k=k%count;
            ListNode slow=head;
            ListNode fast=head;
            while(k>0){
                fast=fast.next;
                k--;
            }
            while(fast.next!=null){
                fast=fast.next;
                slow=slow.next;
            }
            fast.next=head;
            prev.next=slow.next;
            slow.next=null;
            return prev.next; 
        }
  • 相关阅读:
    python的json模块介绍
    采用boosting思想开发一个解决二分类样本不平衡的多估计器模型
    kappa系数
    android服务
    Android Studio 无法预览布局问题:com/android/util/PropertiesMap
    pitch yaw roll是什么
    keil5破解
    Eclipse/jre/jdk/jvm
    传感器
    Java静态代码块
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5472496.html
Copyright © 2011-2022 走看看