0

我创建了一个单链表,但我不断收到 NullPointerException。insert 方法应该将一个对象添加到单链表,然后我将 SLL 的所有元素放入 MyVector 类中,然后使用我为 MyVector 类制作的快速排序算法,然后将对象放回 SSL。我不完全确定为什么我不断收到错误。

在 collection.SortedSLList.remove(SortedSLList.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;
}
4

2 回答 2

1

异常跟踪表明您正在调用 remove(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;
}

然后观察这些价值观在做什么。您会看到其中一个为空。

于 2012-11-04T20:13:45.450 回答
0

问题是你在哪里做:

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

问题是您已经移除了头部 (t),因此您应该将 t 设置为head.data,而不是head.next

于 2012-11-04T19:51:40.203 回答