【LeetCode】 Rotate List 迴圈鏈表

來源:互聯網
上載者:User

標籤:leetcode   鏈表   迴圈鏈表   

題目:rotate list

解法1:

<span style="font-size:18px;">/**LeetCode Rotate List:Given a list, rotate the list to the right by k places, where k is non-negative. * 題目:迴圈移動鏈表,等價於將鏈表從右邊數的k個節點移動到表的前方 * 思路:移動倒是簡單,重點是要找到鏈表倒數的k個數,就等價於找到倒數第K+1個數,設定兩個指標,先後遍曆鏈表,中間相隔k個數 * 當前面的指標走到最後的一個節點,此時後面的指標指向的就是倒數第k+1個數 * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */ package javaTrain;public class Train14 { public ListNode rotateRight(ListNode head, int k) {        ListNode pFast,pSlow,pKnode;        int n = 0;                if(head == null || k < 1 ) return head;//注意特殊情況        pFast = head;        pSlow = head;        while(pFast != null){        pFast = pFast.next;        n++;        }        k = k%n;//迴圈移動,可以轉變為求模        if(k == 0) return head;//移動的次數等於自己的長度,等價於本身        pFast = head;        while(k>0 && pFast != null){         pFast = pFast.next;        k--;        }         while(pFast.next != null){        pFast = pFast.next;        pSlow = pSlow.next;        }        pKnode = pSlow.next;//第k+1個節點,次後就是要移到前面的節點了,        pSlow.next = null;        pFast.next = head;//原本最後的節點此時排在頭結點之前                return pKnode;    } }</span>

解法2:

<span style="font-size:18px;">//法2:將鏈表連城環,而後從新尋找新的頭結點和尾節點,即在len-k處package javaTrain;public class Train14_1 {public ListNode rotateRight(ListNode head, int k) {if(head == null || k == 0) return head;//特殊情況ListNode pNode = head;int len = 1;while(pNode.next != null){pNode = pNode.next;len++;}k = len-k%len;pNode.next = head;//注意此時pNode是原來的尾節點for(int i = 0;i < k;i++){pNode = pNode.next;}head = pNode.next;pNode.next = null;return head;}}</span>


【LeetCode】 Rotate List 迴圈鏈表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.