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; 
        }
  • 相关阅读:
    BEC listen and translation exercise 44
    中译英12
    BEC listen and translation exercise 43
    中译英11
    BEC listen and translation exercise 42
    中译英10
    BEC listen and translation exercise 41
    中译英9
    BEC listen and translation exercise 40
    中译英8
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5472496.html
Copyright © 2011-2022 走看看