理解單鏈表的反轉(java實現)

來源:互聯網
上載者:User

標籤:eve   優雅   des   code   img   輸入   方便   鏈表   reverse   

要求很簡單,輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
??反轉鏈表是有2種方法(遞迴法,遍曆法)實現的,面試官最愛考察的演算法無非是斐波那契數列和單鏈表反轉,遞迴方法實現鏈表反轉比較優雅,但是對於不瞭解遞迴的同學來說還是有理解難度的。

遞迴法

總體來說,遞迴法是從最後一個Node開始,在彈棧的過程中將指標順序置換的。

為了方便理解,我們以 1->2->3->4這個鏈表來做示範。輸出的效果是4->3->2->1

首先定義Node:

public static class Node {    public int value;    public Node next;    public Node(int data) {        this.value = data;    }}

反轉方法如下:

public Node reverse(Node head) {    if (head == null || head.next == null)        return head;    Node temp = head.next;    Node newHead = reverse(head.next);    temp.next = head;    head.next = null;    return newHead;}

遞迴實質上就是系統幫你壓棧的過程,系統在壓棧的時候會保留現場。

我們來看是怎樣的一個遞迴過程:1->2->3->4

  • 程式到達Node newHead = reverse(head.next);時進入遞迴
  • 我們假設此時遞迴到了3結點,此時head=3結點,temp=3結點.next(實際上是4結點)
  • 執行Node newHead = reverse(head.next);傳入的head.next是4結點,返回的newHead是4結點。
  • 接下來就是彈棧過程了
  • 程式繼續執行 temp.next = head就相當於4->3
  • head.next = null 即把3結點指向4結點的指標斷掉。
  • 返回新鏈表的頭結點newHead

    注意:當retuen後,系統會恢複2結點壓棧時的現場,此時的head=2結點;temp=2結點.next(3結點),再進行上述的操作。最後完成整個鏈表的翻轉。

    遍曆法

    遍曆法就是在鏈表遍曆的過程中將指標順序置換

    先上代碼:

    public static Node reverseList(Node node) {Node pre = null;Node next = null;while (node != null) {    next = node.next;    node.next = pre;    pre = node;    node = next;}return pre;}
    依舊是1->2->3->4
  • 準備兩個空結點 pre用來儲存先前結點、next用來做臨時變數
  • 在頭結點node遍曆的時候此時為1結點
    • next = 1結點.next(2結點)
    • 1結點.next=pre(null)
    • pre = 1結點
    • node = 2結點
  • 進行下一次迴圈node=2結點
    • next = 2結點.next(3結點)
    • 2結點.next=pre(1結點)=>即完成2->1
    • pre = 2結點
    • node = 3結點
  • 進行迴圈...

理解單鏈表的反轉(java實現)

聯繫我們

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