0

単一リンク リストを作成しましたが、NullPointerException が引き続き発生します。挿入メソッドは、Singly Linked List にオブジェクトを追加することになっています。次に、SLL のすべての要素を取得して MyVector クラスに配置し、MyVector クラス用に作成したクイック ソート アルゴリズムを使用して、オブジェクトを SSL に戻します。なぜエラーが発生し続けるのか、完全にはわかりません。

スレッド「メイン」で例外 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) で 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;
}

次に、それらの値が何をしているかを観察します。そのうちの 1 つが null になることがわかります。

于 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 に答える