将对象/整数插入单个链接列表并对其进行排序



我已经完成了一个单独的链接列表,但是我一直在获得NullPoInterException。插入方法应该将对象添加到单个链接列表中,然后我将SLL的所有元素放入MyVector类中,然后使用我为MyVector类制作的快速排序算法,然后将对象放回SSL中。我不确定为什么要遇到错误。

线程中的异常" main" java.lang.nullpointerexception 在java.lang.integer.compareto(integer.java:978) 在java.lang.integer.compareto(integer.java:37) 在collection.sortedsllist.remove(sortedsllist.java:51) 在collection.sortedsllist.insert(sortedsllist.java:39) 在lab.lab6.test(lab6.java:15) 在main.main.main(main.java:15) Java结果:1

public void insert(Object element) {
    if(head == null) {
        head = tail = new SLListNode(element, null);
        ++size;
        return;
    }
    tail = tail.next = new SLListNode(element, null);
    ++size;
    MyVector temp = new MyVector();
    int i = size;
    Object t = head.data;
    while(temp.size() < i) {
        temp.append(t);
        remove(t); //this line
        t = head.next;
    }
    MySort.quickSort(temp);
    i = 0;
    while(size < temp.size()) {
        insert(temp.elementAt(0));
        ++i;
    }
}
public boolean remove(Object element) {
    if(head == null) return false;
    if(((Comparable)(head.data)).compareTo(element) == 0) { //this line
        if(head == tail) {
            head = tail = null;
            return true;
        }
        head = head.next;
        return true;
    }
    if(head == tail) return false;
    SLListNode ref = head;
    while(ref.next != tail) {
        if(((Comparable)(ref.next.data)).compareTo(element) == 0) {
            ref.next = ref.next.next;
            return true;
        }
        ref = ref.next;
    }
    if(((Comparable)(tail.data)).compareTo(element) == 0) {
        tail = ref;
        tail.next = null;
        return true;
    }
    return false;
}

异常跟踪表示您正在调用删除(null)。由于某种原因,head.data或head.next包含null。我建议您在此处添加打印输出:

Object t = head.data;
while(temp.size() < i) {
    System.out.println("Looking at " + t); // <-- add here
    temp.append(t);
    remove(t); //this line
    t = head.next;
}

然后观察这些值在做什么。您会看到其中一个出现null。

问题是您要做的地方:

while(temp.size() < i) {
    temp.append(t);
    remove(t); //this line
    t = head.next;
}

问题是您已经删除了头(t),因此您应该将t等于head.data,而不是head.next

最新更新