双链表的问题。将一个迭代是什么样的?

问题描述 投票:1回答:1
class Node {

public Node prev;
public int item;
public Node next;

public Node(Node p, int i, Node n) {
    prev = p;
    item = i;
    next = n;
}

}

这是节点类。

这就是我要看看通过。

p = list; 
while ( p != null) {     
   q = p.next;     
   p.next = p.prev;     
   p.prev = q;     
   list = p;     
   p = q; 
};     

我的节点列表最初是这样的:空 - > 1 - > 2 - > 3 - > 4 - > 5 - >空

这是我竟能通过while循环1次,我只是想确保它是正确的。

列表= NULL 2 3 4 5 1空

P =空2 3 4 5空

Q =空2 3 4 5空

我对格式道歉,我是新来的堆栈溢出张贴。

java doubly-linked-list
1个回答
0
投票

您的代码实际上是恢复双向链表。

第一次迭代后,具体来说,你有下列情形:

p: null -> 2 -> 3 -> 4 -> 5 -> null
q: null -> 2 -> 3 -> 4 -> 5 -> null
list: null -> 1 -> null

这里是你如何看待你的方法迭代,通过迭代的状态:

class Answer {
  static class Node {
    int item;
    Node prev;
    Node next;

    Node(int item) {
      this.item = item;
      this.prev = null;
      this.next = null;
    }

    static Node of(int item) {
      return new Node(item);
    }

    Node link(Node next) { 
      this.next = next;
      next.prev = this;
      return next;
    }

    @Override
    public String toString() {
      String res = "null -> " + this.item + " -> ";
      Node node = this;
      while (node != null) {
        res += (node.next == null) ? "null" : (node.next.item + " -> ");
        node = node.next;
      }
      return res;
    }
  }

   public static void main(String[] args) {
    // initialize: null -> 1 -> 2 -> 3 -> 4 -> 5 -> null
    Node root = Node.of(1);
    root.link(Node.of(2))
        .link(Node.of(3))
        .link(Node.of(4))
        .link(Node.of(5));
    reverse(root);
  }

  static void reverse(Node list) {
    int iteration = 1;
    Node p = list; 
    Node q = null;
    while ( p != null) {
       q = p.next;     
       p.next = p.prev;     
       p.prev = q;     
       list = p;     
       p = q; 
       printIteration(iteration++, p, q, list);
    }
  }

  static void printIteration(int iteration, Node p, Node q, Node list) {
    System.out.println();
    System.out.println("iteration " + iteration);
    System.out.println("p: " + p);
    System.out.println("q: " + q);
    System.out.println("list: " + list);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.