【问题标题】:Inserting an Object/Integer into a Singly Linked List and sorting it将对象/整数插入单链表并对其进行排序
【发布时间】:2012-10-24 16:47:41
【问题描述】:

我创建了一个单链表,但我不断收到 NullPointerException。 insert 方法应该将一个对象添加到单链表,然后我将 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;
}

【问题讨论】:

  • 您能否发布您的堆栈跟踪信息,或者让我们知道错误出现在哪一行
  • 不确定堆栈跟踪是什么,但我标记了代码中的行并添加了 NetBeans 给我的错误消息。
  • 您发布的异常是堆栈跟踪 ..:)
  • 这是对插入的递归调用吗?它是如何工作的?

标签: java list sorting linked-list


【解决方案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;
}

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

【讨论】:

    【解决方案2】:

    问题在于你在哪里做:

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

    问题是你已经移除了头部 (t),所以你应该设置 t 等于 head.data,而不是 head.next

    【讨论】:

    • 其实我猜应该是head.data,因为你删除的是数据,而不是节点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 2011-08-13
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多