双向链表不会向后打印

问题描述 投票:0回答:2

在下面的双向链接列表示例中,我可以将节点添加到双向链接列表的前面和双向链接列表的末尾。我还可以向前遍历双向链表,并成功打印节点的值。当我向后打印列表时,尾声太高了。以前的值为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
2个回答
0
投票

您的addToBack方法未设置新节点的上一个指针。

添加此:

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

0
投票

您必须指向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;
}
© www.soinside.com 2019 - 2024. All rights reserved.