2016-10-10 55 views
0

我正在實現一個抽象類,並實現了插入排序列表的insert方法。這是遞歸的方法我到目前爲止:java - 排序列表遞歸插入方法

public void insert(E data) { 
    Node<E> temp = head; 
    insert(temp, data); 
} 

private void insert(Node<E> curr, E data){ 
    Node<E> temp = new Node<E>(data); 
    if (head == null || data.compareTo(head.data) < 0) { 
     temp.next = head; 
     head = temp; 
    } 
    else if(curr.data.compareTo(data) < 0 && (curr.next == null || curr.next.data.compareTo(data) > 0)){ 
     temp.next = curr.next; 
     curr.next = temp; 
     return; 
    } 
    else{ 
     insert(curr.next, data); 
    } 
} 

但是,任何時候我嘗試插入2+物品進入名單,我得到一個空指針異常錯誤。有人能解釋我的錯誤嗎?這是當我嘗試運行它簡單地插入1和2會發生什麼:https://gyazo.com/d254d563675b9d1b0efbce443eda4445

回答

1

它說,有一個NullPointerException在53行,這是其他-if語句:

else if(curr.data.compareTo(data) < 0 && curr.next.data.compareTo(data) > 0) 

我認爲這因爲curr.next爲空而給出該例外。從我可以看到的方式,當你添加第一個元素你初始化頭,但head.next爲空(temp.next = head爲空,因爲當時頭爲空)。因此,當您嘗試添加第二個元素時,您無法訪問curr.next.data並且它會給出NullPointerException。

+0

我該如何處理? – witcheR

+0

一個簡單的方法是啓動else if(curr.data!= null && curr.next!= null)。 if條件一旦爲空並且一直到最後的else都將是假的。但這不是根本問題。根本問題是你試圖管理一些可以通過其他方式更好地處理的事情的方法,例如追加到列表然後使其具有唯一性。 –

+0

'else if(curr.data.compareTo(data)<0 &&(curr.next == null || curr.next.data.compareTo(data)> 0)'可能可以解決問題,就像else中一樣if塊要添加數據iff curr> data> curr.next和curr.next = null意味着數據是最小的元素 – merterpam