Datenstruktur – Wie wird eine umgedrehte verknüpfte Java-Liste implementiert?
習慣沉默
習慣沉默 2017-06-23 09:13:13
0
2
879
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;


    }

Wie dreht sich dieser Code in der while-Schleife? Ich habe ihn mehrmals debuggt und kann immer noch nicht herausfinden, was los ist

習慣沉默
習慣沉默

Antworte allen(2)
大家讲道理

参考一下,理解目的就比较好理解了。容易混乱的地方就是从右往左来处理,因为得先把后面的东西存起来,不然被覆盖掉就丢了。

 pre        head       
+----+     +----+  +> +----+
|    |     |    |  |  |    |
|    |     |    |  |  |    |
|    |     |    |  |  |    |
+----+     +----+  |  +----+
|    |     |    |  |  |    |
|    |     |    |  |  |    |
+----+     +-+--+  |  +----+
             |     |
             +-----+

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

 pre        head       next
+----+ <+  +----+     +----+
|    |  |  |    |     |    |
|    |  |  |    |     |    |
|    |  |  |    |     |    |
+----+  |  +----+     +----+
|    |  |  |    |     |    |
|    |  |  |    |     |    |
+----+  |  +-+--+     +----+
        |    |                     head.next = pre;
        +----+
                       next
            pre        head        pre = head;
+----+ <+  +----+     +----+       head = next;
|    |  |  |    |     |    |
|    |  |  |    |     |    |
|    |  |  |    |     |    |
+----+  |  +----+     +----+
|    |  |  |    |     |    |
|    |  |  |    |     |    |
+----+  |  +-+--+     +----+
        |    |
        +----+
过去多啦不再A梦

Ps:建议先多了解一下链表

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage