【Leetcode】Rotate List

【題目】

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.


【思路】

實質就是n-k個元素挪到了鏈子的前面, 第n-k個元素變成新head,最後一個元素鏈接當前的head


注意起始邊緣條件,如果head是空,只有一個元素,或者k=0,都只要返回head就可以。

首先找到這個list的長度 n, 方法就是遍歷一遍咯。

得到長度以後,我們就知道是哪後幾個挪過來。

注意細節!!:

k的值有可能大於n!! 所以 step = n - n%k,
找到最後一個元素之後,最後一個元素就可以直接連接到head了

這時候可以繼續用h這個變量,因爲已經連接上head了,而且位置在head之前,正好!可以經過step步以後達到新head的前一個,然後把h .next賦給新的headNode,在變成空。(因爲隊尾下一個要賦值爲空!)就OK了!

【代碼】

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null || k ==0) return head;
        
        ListNode h = head;
        int n = 1;
        while(h.next != null){
            n++;
            h = h.next;
        }
     <span style="background-color: rgb(255, 255, 153);">   h.next = head;</span>
        int step = n - k%n;
     
        for(int i = 0 ; i <step;i++){
            h = h.next;
        }
        ListNode NHead = h.next;
        h.next = null;
       
        return NHead;
      


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