首页  >  问答  >  正文

数据结构 - 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了几次还是没弄懂具体是怎么回事

習慣沉默習慣沉默2675 天前842

全部回复(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
  • 取消回复