码迷,mamicode.com
首页 > 其他好文 > 详细

61. Rotate List

时间:2016-05-09 06:56:57      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

    /*
     * 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; 
    }

 

61. Rotate List

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5472496.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!