简体   繁体   中英

Generic Doubly Linked List Implementation

So I have this basic generic implantation of generic doubly linked list. I have created an insert method which is going to add a node according to the order.

public class DoublyLL <T extends Comparable<T>> {
DNode<T> head;
DNode<T> tail;

public void insertInOrder(T item) { //To create an "ordered" linked list
    DNode <T> n = new DNode<>();

    if (head == null) {
        head = n;
        n.data = item;
    }
    else {
        DNode<T> temp = head;
        while (temp != null && n.data.compareTo(temp.data) > 0) { // line 18
            temp = temp.next;
        }
        if (temp == head) { //inserting node in first
            head.prev = n;
            n.next = head;
            head = n;
            n.data = item;
        }
        else if (temp == null) { // inserting at last
            tail.next = n;
            n.prev = tail;
            tail = n;
            n.data = item;
        }

        else { //inserting in middle
            n.prev = temp.prev;
            n.next = temp;
            temp.prev.next = n;
            temp.prev = n;
            n.data = item;
        }
     }


    }

@Override
public String toString() {
    DNode temp = head;
    String str = "";
    while (temp != null) {
        str += temp.data + " ";
        temp = temp.next;
    }
    return str;
}



public static void main(String[] args) {
    DoublyLL<Integer> list = new DoublyLL<>();
    list.insertInOrder(2);
    list.insertInOrder(222); //line 62
    list.insertInOrder(22222);
    System.out.println(list);

}
}

class DNode<T> {
T data;
DNode prev;
DNode next;
}

However, when I'm running this I'm getting the NullPointerException at line 18 and 62. What can I do to get rid of that to make the ordered list like, "2, 22, 2222?

It's hard to say what's the problem without stack trace but it looks like instead of

if (head == null) {
    head = n;
    n.data = item;
}

you should have

if (head == null) {
    head = n;
    tail = n;
    n.data = item;
}

Otherwise your tail remains null.

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