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

    Given a list, rotate the list to the right by k places, where k is non-negative.

    For example:
    Given 1->2->3->4->5->NULL and k = 2,
    return 4->5->1->2->3->NULL.

     此题先想需要多少个ListNode,dummy,用于返回。fast,slow。三个就够了,我开始做的时候,多用了一个cur来计算链表长度,我的原始代码如下:

    /**

     * Definition for singly-linked list.

     * public class ListNode {

     *     int val;

     *     ListNode next;

     *     ListNode(int x) { val = x; }

     * }

     */

    public class Solution {

        public ListNode rotateRight(ListNode head, int k) {

            ListNode slow = head;

            ListNode fast = head;

            ListNode cur = head;

            ListNode dummy = new ListNode(0);

            if(head==null) return head;

            int len = 0;

            while(cur!=null){

                cur=cur.next;

                len++;

            }

            k = k%len;

            if(k==0) return head;

            while(k>0){

                fast = fast.next;

                k--;

            }

            while(fast!=null&&fast.next!=null){

                fast = fast.next;

                slow = slow.next;

            }

            fast.next = head;

            dummy.next = slow.next;

            slow.next = null;

            return dummy.next;

        }

    }

    看了答案以后,发现答案的方法很简明,答案代码如下:

     

    /**

     * Definition for singly-linked list.

     * public class ListNode {

     *     int val;

     *     ListNode next;

     *     ListNode(int x) { val = x; }

     * }

     */

    public class Solution {

        public ListNode rotateRight(ListNode head, int k) {

            ListNode dummy = new ListNode(0);

            ListNode slow = dummy;

            ListNode fast = dummy;

            dummy.next = head;

            if(head==null||head.next==null) return head;

            int len = 0;

            while(fast.next!=null){

                fast = fast.next;

                len++;

            }

            k = k%len;

            while(len-k>0){

                slow = slow.next;

                len--;

            }

            fast.next = dummy.next;

            dummy.next = slow.next;

            slow.next = null;

            return dummy.next;

        }

    }

     
     
  • 相关阅读:
    prepareSlideshow函数
    moveElement函数与positionMessage函数
    function styleElementSiblings函数与 addClass函数
    stribeTables函数与highlightRows函数
    确定股票见底的六大信号
    调整期六招教你猎杀未来牛股
    王者-甄别同一板块强弱股的方法【真假美猴王】
    王者--分时图五要素教你抓涨停板股票
    王者-【注册制将利好哪些股票】
    王者--看盘口特点猎杀强庄股
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6363909.html
Copyright © 2011-2022 走看看