61.Rotate List

題目

給出一個鏈表,將鏈表旋轉到右邊的第k個位置,其中k是非負的。

例1:
輸入: 1->2->3->4->5->NULL, k = 2
輸出:4->5->1->2->3->NULL

例2:
輸入: 0->1->2->NULL, k = 4
輸出:2->0->1->NULL
解釋 :
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

代碼塊

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null) return head;
        int len = 1;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode fastNode = head;
        while(fastNode.next != null){//這個判斷條件是關鍵。
            fastNode = fastNode.next;
            len++;
        }
        ListNode slowNode = head;
        for(int i = 0; i < len - k%len - 1; i++){
            slowNode = slowNode.next;
        }
        fastNode.next = dummy.next;
        dummy.next = slowNode.next;
        slowNode.next = null;
        return dummy.next;
    }
}

代碼分析

本題的代碼分爲3部分。
第一是計數,即鏈表的長度。
第二是找到要旋轉的結點的位置分界線,即看它在原鏈表中的前置節點(爲新鏈表的頭結點)。
第三是交換順序。
注意:k如果超過鏈表的長度,需要進行模運算。

遇到的問題: 計數時判斷條件搞錯了。寫成head(head.next)!=null ,這是不對的,因爲head是不會變的。fastNode會變。有點混亂。

ListNode fastNode = new ListNode(0);
fastNode = head;

等價於
ListNode fastNode = head; 

然後就是默寫LeetCode的時候第一句就判斷錯了,應該是== null 返回head;自己寫成了非等。失誤。

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