LeetCode題解-61-Rotate List

原題


感覺這題沒有交代清楚細節,解釋一下。本題是將最後K個節點移動到頭部,其中k如果大於鏈表的長度的話,k要根據鏈表的長度取餘再做變化。例如,示例中鏈表長度爲5,那麼當k=7的時候,K = K %5 = 2,返回4->5->1->2->3->NULL


解法概要

該題共有2種解法

Ⅰ、快慢指針

Ⅱ、將原鏈表變爲循環鏈表(參考別人解法),更加簡單


解法1:快慢指針

解題思路

使fast指針領先slow指針k個節點,當fast指針到達尾部的時候,slow指針指向的正好是需要變更鏈接關係的節點。


圖解



代碼

public class Solution61 {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null || k <= 0)
            return head;

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode slow = dummy , fast = dummy, iterator = head;
        int length = getListLength(head);

        //初始化fast的位置
        for (int i = 0; i < k % length; i++){
            fast = fast.next;
        }

        //移動slow與fast
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next;
        }

        fast.next = dummy.next;
        dummy.next = slow.next;
        slow.next = null;

        return dummy.next;
    }

    private int getListLength(ListNode head) {
        int count = 0;
        ListNode iterator = head;
        while (iterator != null){
            iterator = iterator.next;
            count++;
        }
        return count;
    }
}

解法2:循環鏈表


解題思路

將鏈表連接成環,tail前進對應的步數,在對應的位置重新將鏈表斷開。

代碼

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head) return head;

        int len=1; // number of nodes
        ListNode *newH, *tail;
        newH=tail=head;

        while(tail->next)  // get the number of nodes in the list
        {
            tail = tail->next;
            len++;
        }
        tail->next = head; // circle the link

        if(k %= len) 
        {
            for(auto i=0; i<len-k; i++) tail = tail->next; // the tail node is the (len-k)-th node (1st node is head)
        }
        newH = tail->next; 
        tail->next = NULL;
        return newH;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章