LeetCode:旋轉鏈表【61】

來源:互聯網
上載者:User

標籤:col   leetcode   scan   ret   問題   ext   迴圈   img   負數   

LeetCode:旋轉鏈表【61】題目描述

給定一個鏈表,旋轉鏈表,將鏈表每個節點向右移動 個位置,其中 是非負數。

樣本 1:

輸入: 1->2->3->4->5->NULL, k = 2輸出: 4->5->1->2->3->NULL解釋:向右旋轉 1 步: 5->1->2->3->4->NULL向右旋轉 2 步: 4->5->1->2->3->NULL

樣本 2:

輸入: 0->1->2->NULL, k = 4輸出: 2->0->1->NULL解釋:向右旋轉 1 步: 2->0->1->NULL向右旋轉 2 步: 1->2->0->NULL向右旋轉 3 步: 0->1->2->NULL向右旋轉 4 步: 2->0->1->NULL
題目分析

  這道題目我用了最笨的方法,我假設每次只向右旋轉一個單位,然後執行N次

  向右旋轉一個單位怎麼處理呢?

  找到最後兩個節點,讓最後一個節點的next指向第一個節點,然後倒數第二個節點的next指向空。

  

  處理一個問題,對於迴圈次數我們可以用求餘數來提高效率,比如長度為5,那麼迴圈10000次也還是原來的就不需要迴圈。

Java題解
package linklist;import java.util.Scanner;public class RotateList_61 {    public static void main(String[] args) {        ListNode node1 = new ListNode(1);        ListNode node2 = new ListNode(2);        ListNode node3 = new ListNode(3);        ListNode node4 = new ListNode(4);        ListNode node5 = new ListNode(5);        node1.next=node2;        node2.next=node3;        node3.next=node4;        node4.next=null;        new RotateList_61().rotateRight(node1,2);    }    public ListNode rotateRight(ListNode head, int k) {        if(head==null)            return null;        int len = getLen(head);        for(int i = 0;i<k%len;i++)        {            head = rotateRight(head);        }        return head;    }    public ListNode rotateRight(ListNode head) {        ListNode ptrL = head;        ListNode ptrR = ptrL.next;        if(ptrR==null)            return head;        while (ptrR.next!=null)        {            ptrL=ptrL.next;            ptrR=ptrR.next;        }        ptrR.next=head;        ptrL.next=null;        return ptrR;    }    public static int getLen(ListNode node)    {        int count = 0;        while (node!=null)        {            count++;            node=node.next;        }        return count;    }}

 

LeetCode:旋轉鏈表【61】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.