簡體   English   中英

將對象/整數插入單鏈列表並對其進行排序

[英]Inserting an Object/Integer into a Singly Linked List and sorting it

我已經創建了一個單鏈接列表,但是我一直收到NullPointerException。 應該使用insert方法將對象添加到單鏈列表,然后將SLL的所有元素放入MyVector類中,然后使用為MyVector類制作的快速排序算法,然后將對象放回SSL中。 我不太確定為什么我總是收到錯誤消息。

集合“ SortedSLList.remove(SortedSLList)處的java.lang.Integer.compareTo(Integer.java:37)處的java.lang.Integer.compareTo(Integer.java:978)處的線程“ main”中的異常java.lang.NullPointerException。 Java:51)at collection.SortedSLList.insert(SortedSLList.java:39)at lab.Lab6.test(Lab6.java:15)at 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;
}

異常跟蹤表明您正在調用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;
}

然后觀察這些值在做什么。 您會看到其中之一出現為空。

問題是您在哪里做:

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

問題在於您已經刪除了head(t),因此應將t設置為等於head.data ,而不是head.next

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM