2012-11-04 41 views
0

我製作了一個單鏈表,但我不斷收到NullPointerException。插入方法應該添加一個對象到單獨鏈接列表,然後我把SLL的所有元素放到MyVector類中,然後使用我爲MyVector類創建的快速排序algorythm,然後將對象放回到SSL中。我不完全確定爲什麼我一直在收到錯誤。將對象/整數插入單鏈表並對其進行排序

在java.lang.Integer.compareTo(Integer.java:37)在線程 「主」 顯示java.lang.NullPointerException 在java.lang.Integer.compareTo(Integer.java:978) 異常 在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結果: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; 
} 
+2

你可以發佈你的堆棧跟蹤,或者讓我們知道錯誤是什麼行 – PermGenError

+0

不知道什麼stacktrace是,但我標記了代碼中的行,並添加了NetBeans給我的錯誤消息。 – Schwarz

+0

你發佈的異常是stacktrace .. :) – PermGenError

回答

0

問題是,你做的事:

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

的問題是,您已刪除打印頭(T),所以你應該是T設置等於head.data,不head.next

+0

我剛試過這個改變,它產生了相同的結果。 – Schwarz

+0

其實我猜它應該是'head.data',因爲你正在刪除數據,而不是節點。 – CrazyCasta

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; 
} 

然後看看這些值在做什麼。你會看到其中一個出現null。