在下面的双链表示例中,我可以将节点添加到双链表的前面和双链表的末尾我还可以向前遍历双链表并成功打印节点的值。当我把列表向后打印时。前一个值是空的,我只能打印当前在尾部的节点的值。你能告诉我出了什么问题吗谢谢您。
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();
}
}
最佳答案
addToBack方法没有设置新节点的上一个指针。
添加以下内容:
if (tail != null) {
tail.next = nn;
nn.prev = tail;
}
关于java - 双链表不会向后打印,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58251166/