[LeetCode] 61. Rotate List java

    /**61. Rotate List 
     * @param head
     * @param k
     * @return 成環後右移k位
     */
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || k == 0) {
            return head;
        }
        ListNode cur = head;
        int len = 0;
        while (cur != null) {
            cur = cur.next;
            len += 1;
        }
        k = k%len;
        if(k == 0)
            return head;

        ListNode ret = new ListNode(-1);
        ListNode fast = head;
        ListNode fastPre = ret;
        ListNode slow = head;
        ListNode slowPre = ret;
        int count = 0;
        while (fast != null) {
            if (count < k) {
                count += 1;
            } else {
                slowPre = slow;
                slow = slow.next;
            }
            fastPre = fast;
            fast = fast.next;
        }
        if (slow == head) {
            return head;
        } else {
            slowPre.next = null;
            ret.next = slow;
            fastPre.next = head;
            return ret.next;
        }
    }

/**循環後移k>len,要取餘
* 之後fast,slow隔開k位直到fast走到隊尾,slow就是新鏈表的頭,拼接
* */

還可以成環之後,移動

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章