简体   繁体   中英

Doubly linked list does not print backwards

In below doubly linked list example I can add node to front of the doubly linked list and the end of the doubly linked list. I also can traverse the doubly linked list forward and print the node's value successfully. Hoewer when I print the list backwards my tail.previous value is null and I can print only the node's value that is currently in the tail Could you please tell what is wrong. Thank you.

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;      
    }

 }
}

The test code is below: 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();
 }
}

Your addToBack method is not setting the prev pointer of the new node.

Add this:

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

you have to point back in addToback method

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM