在下面的双向链接列表示例中,我可以将节点添加到双向链接列表的前面和双向链接列表的末尾。我还可以向前遍历双向链表,并成功打印节点的值。当我向后打印列表时出现乱码.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();
}
}
答案 0 :(得分:1)
您的addToBack方法未设置新节点的上一个指针。
添加此内容:
if (tail != null) {
tail.next = nn;
nn.prev = tail;
}
答案 1 :(得分: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;
}