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; 
        }
  • 相关阅读:
    深入分析String类型(一)
    创建泛型类
    XML数据的读取—数据库配置文件
    Config配置文件读写
    jQuery动画
    设置屏幕快捷键
    jQuery事件
    jQuery操作DOM
    Python 二进制文件网址
    Centos使用crontab自动定时备份mysql的脚本
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5472496.html
Copyright © 2011-2022 走看看