【Lintcode】170. Rotate List

題目地址:

https://www.lintcode.com/problem/rotate-list/description

給定一個鏈表,再給定一個正整數kk,要求將鏈表向右旋轉kk步。旋轉11步的意思是,將每個node的位置向右移動一格,最後一個node移動到鏈表首位。

思路是,找到倒數第k+1k+1個節點,將鏈表尾部連接到鏈表頭,然後將倒數第k+1k+1個節點與後面斷開,再返回新鏈表的頭即可。需要注意的是,如果kk大於鏈表長度,在找倒數第k+1k+1個節點的時候會出錯,所以要先求表長,再取餘。代碼如下:

public class Solution {
    /**
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    public ListNode rotateRight(ListNode head, int k) {
        // write your code here
        // 如果鏈表長度爲0,取餘會出錯,所以對空表單獨考慮
        if (head == null) {
            return null;
        }
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        int l = len(head);
        k %= l;
        
        ListNode slow = dummy, fast = dummy;
        for (int i = 0; i < k; i++) {
            fast = fast.next;
        }
        
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        
        fast.next = head;
        // 先緩存新鏈表的表頭,再斷開
        ListNode res = slow.next;
        slow.next = null;
        
        return res;
    }
    
    private int len(ListNode head) {
        int res = 0;
        while (head != null) {
            res++;
            head = head.next;
        }
        return res;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
}

時間複雜度O(n)O(n),空間O(1)O(1)

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