1. 程式人生 > 實用技巧 >Leetcode61.旋轉連結串列

Leetcode61.旋轉連結串列

題目連結:61.旋轉連結串列

思路:右移k個位置就是將連結串列右邊的k個節點放到表頭。那麼就讓1個指標從表頭先走k-1步(算上表頭節點此時一共經過k個節點),然後再讓一個指標從表頭出發,此時兩個指標含有k個節點,當先走的指標到達連結串列尾部,那麼兩個指標所包含的節點就是要右移到表頭的節點。

程式碼:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null) return head;
        int len = 0;
        for(ListNode p=head; p!=null; p=p.next) len++;
        k = k % len;
        if(k == 0) return head;
        ListNode fir = head, sec = head, pre = null;
        while(k-- > 1) fir = fir.next;
        while(fir.next != null){
            pre = sec;
            fir = fir.next;
            sec = sec.next;
        }
        fir.next = head;
        pre.next = null;
        return sec;
    }
}

*執行用時: 1 ms
記憶體消耗: 37.9 MB
*