搜尋

首頁  >  問答  >  主體

資料結構 - java翻轉鍊錶是如何實現的?

public class Node {
    public int value;
    public Node next;

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


    public Node reverse(Node head) {
        Node pre = null;
        Node next = null;

        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;

        }
        return pre;


    }

這段程式碼while循環中他是如何翻轉的?想要詳細一點的,debug了幾次還是沒弄懂具體是怎麼回事

習慣沉默習慣沉默2739 天前883

全部回覆(2)我來回復

  • 大家讲道理

    大家讲道理2017-06-23 09:15:13

    參考一下,理解目的就比較好理解了。容易混亂的地方就是從右往左來處理,因為得先把後面的東西存起來,不然被覆蓋掉就丟了。

     pre        head       
    +----+     +----+  +> +----+
    |    |     |    |  |  |    |
    |    |     |    |  |  |    |
    |    |     |    |  |  |    |
    +----+     +----+  |  +----+
    |    |     |    |  |  |    |
    |    |     |    |  |  |    |
    +----+     +-+--+  |  +----+
                 |     |
                 +-----+
    
     pre        head       next        next = head.next;
    +----+     +----+  +> +----+
    |    |     |    |  |  |    |
    |    |     |    |  |  |    |
    |    |     |    |  |  |    |
    +----+     +----+  |  +----+
    |    |     |    |  |  |    |
    |    |     |    |  |  |    |
    +----+     +-+--+  |  +----+
                 |     |
                 +-----+
    
     pre        head       next
    +----+ <+  +----+     +----+
    |    |  |  |    |     |    |
    |    |  |  |    |     |    |
    |    |  |  |    |     |    |
    +----+  |  +----+     +----+
    |    |  |  |    |     |    |
    |    |  |  |    |     |    |
    +----+  |  +-+--+     +----+
            |    |                     head.next = pre;
            +----+
                           next
                pre        head        pre = head;
    +----+ <+  +----+     +----+       head = next;
    |    |  |  |    |     |    |
    |    |  |  |    |     |    |
    |    |  |  |    |     |    |
    +----+  |  +----+     +----+
    |    |  |  |    |     |    |
    |    |  |  |    |     |    |
    +----+  |  +-+--+     +----+
            |    |
            +----+
    

    回覆
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-23 09:15:13

    Ps:建議先多了解一下鍊錶

    回覆
    0
  • 取消回覆