【问题标题】:Doubly linked list does not print backwards双向链表不向后打印
【发布时间】:2019-10-05 18:28:31
【问题描述】:

在下面的双向链表示例中,我可以将节点添加到双向链表的前面和双向链表的末尾。我也可以向前遍历双向链表并成功打印节点的值。当我向后打印列表时,我的 tail.previous 值为 null 并且我只能打印当前位于尾部的节点的值,请您告诉我出了什么问题。谢谢。

public class DLL {

public Node head;
public Node tail;

/* Doubly Linked list Node*/
public class Node { 
    public int data; 
    public Node prev; 
    public Node next; 

    // Constructor to create a new node 
    // next and prev is by default initialized as null 
    Node(int d) { data = d; } 
} 

public void addToFront(int data){
    System.out.println( data + " will be added to the front!");
    Node nn = new Node(data);
    nn.next = head;
    nn.prev = null;
    if (head != null) head.prev = nn;
    head = nn;
    if (tail == null) tail = nn;
}

public void addToBack(int data){
    Node nn = new Node(data);
    System.out.println(data + " will be added to the back!");
    if (tail != null) tail.next = nn;
    tail = nn;
    if (head == null) head = nn;
}

public void printForward(){

    System.out.println("Printing forward!");
    Node runner = head;
    while(runner != null){
        System.out.println(runner.data);
        runner = runner.next;
    }

}
public void printBackward(){

    System.out.println("Printing backwards");
    Node runner = tail;
    while (runner != null){
        System.out.println(runner.data);
        runner = runner.prev;      
    }

 }
}

测试代码如下: 公共类 DDLTest{

public static void main (String[] args){
    DLL dl = new DLL();
    dl.addToFront(2);
    dl.addToFront(1);
    dl.addToBack(3);
    dl.printForward();
    dl.printBackward();
 }
}

【问题讨论】:

    标签: java algorithm


    【解决方案1】:

    您的 addToBack 方法没有设置新节点的 prev 指针。

    添加这个:

        if (tail != null) {
            tail.next = nn;
            nn.prev = tail;
        }
    

    【讨论】:

      【解决方案2】:

      你必须在 addToback 方法中指向回来

      public void addToBack(int data){
          Node nn = new Node(data);
          System.out.println(data + " will be added to the back!");
          if (tail != null){
              tail.next = nn;
              nn.prev = tail;
              tail = nn;
          }
      
      
          if (head == null) head = nn;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 2021-07-24
        • 1970-01-01
        相关资源
        最近更新 更多