Home  >  Q&A  >  body text

Data structure - How is Java flipped linked list implemented?

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;


    }

How does this code flip in the while loop? I want to be more detailed. I debugged it several times and still don’t understand what’s going on.

習慣沉默習慣沉默2675 days ago838

reply all(2)I'll reply

  • 大家讲道理

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

    It will be easier to understand the purpose if you refer to it. The most confusing part is to deal with it from right to left, because you have to save the things at the back first, otherwise they will be overwritten and lost.

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

    reply
    0
  • 过去多啦不再A梦

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

    Ps: It is recommended to learn more about linked lists first

    reply
    0
  • Cancelreply