java - 将对象/整数插入单链表并对其进行排序

标签 java list sorting linked-list

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

Exception in thread "main" java.lang.NullPointerException at java.lang.Integer.compareTo(Integer.java:978) at java.lang.Integer.compareTo(Integer.java:37) at collection.SortedSLList.remove(SortedSLList.java:51) at collection.SortedSLList.insert(SortedSLList.java:39) at lab.Lab6.test(Lab6.java:15) at main.Main.main(Main.java:15) Java Result: 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;
}

最佳答案

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

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

关于java - 将对象/整数插入单链表并对其进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13222128/

相关文章:

Java GridBayLayout 替换组件

java - 如何修复打印为一列的二维数组

c - C中如何将每手牌先按牌值排序,再按花色排序?

python - 根据 Python 中的月份列表制作列表

按键对 Lua 表进行排序

C++/Qt : Get files in directory ordered according to sorting currently applied in Windows Explorer

java - Lambda合并内部对象列表

java - 为什么 getItem(position) 与新实例一起使用? (不应该为零?)

Python:列表中的列表索引超出范围错误

Python - 像操作字符串一样操作列表值