[英]Doubly linked list does not print backwards
在下面的雙向鏈表示例中,我可以將節點添加到雙向鏈表的前面和雙向鏈表的末尾。 我也可以向前遍歷雙向鏈表並成功打印節點的值。 當我向后打印列表時,我的 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;
}
}
}
測試代碼如下: public class 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 方法沒有設置新節點的 prev 指針。
添加這個:
if (tail != null) {
tail.next = nn;
nn.prev = tail;
}
你必須指向 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.