通用双链表实现

时间:2017-09-12 16:02:10

标签: java generics doubly-linked-list

所以我有这个通用双链表的基本通用植入。我创建了一个insert方法,它将根据顺序添加一个节点。

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

然而,当我运行这个时,我在第18行和第62行得到了NullPointerException。我能做些什么来摆脱它,使得有序列表如“2,22,2222?

1 个答案:

答案 0 :(得分:0)

很难说没有堆栈跟踪的问题是什么,但看起来不是

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

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

否则您的tail仍然为空。