繁体   English   中英

通用双链表实现

[英]Generic Doubly Linked List Implementation

所以我有了通用双链表的基本通用植入。 我创建了一个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”?

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

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

你应该有

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

否则,您的tail保持为空。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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