2017-05-25 141 views
0

刪除許多節點時出現問題。雙向鏈表java刪除

我可以將它們刪除,如果我選擇的節點是這樣的:

View

但如果我這樣做,我不能刪除它們:

this

我的代碼:

public boolean remove(ProductNode<E> data) { 
    if (isEmpty()) { 
     throw new NoSuchElementException(); 
    } 
    for (ProductNode<E> current = this.head; current != null; current = current.next) { 
     ProductNode<E> pre = current.prev; 
     ProductNode<E> next = current.next; 
     if (data != null) { 
      if (current.data.equals(data.data)) { 
       if (pre == null) { 
        head = next; 
        current.next = null; 
       } else { 
        if (next != null) { 
         next.prev = pre; 
        } 
       } 
       if (next == null) { 
        pre.next = null; 
        current.prev = null; 
        tail = pre; 
       } else { 
        if (pre != null) { 
         pre.next = next; 
        } 

       } 
      } 

     } 
    } 
    size--; 
    return false; 
} 

搜索節點

public ProductNode<E> search(E data) { 
    for (ProductNode<E> current = this.head; current != null; current = current.next) { 
     if (current.data.equals(data)) { 
      return current; 
     } 
    } 
    return null; 
} 

刪除

public void remove(E e) { 
    remove(search(e)); 
} 

刪除:

for(Tab_Product p : remove_list){ 
     List_Products.list_products.remove(p); 
    } 
+0

你有沒有嘗試用調試器逐步完成代碼?這可能會使得它更清楚發生了什麼,以及何時(如果在刪除相鄰節點時發生問題,或者刪除列表中的第一個節點時發生問題) – whrrgarbl

回答

0

你刪除功能(ProductNode數據),是有點複雜,可能會影響您的代碼刪除多個節點的能力。在這個刪除功能的情況下,你不需要遍歷整個數據集。如果您已經有了對節點的引用,那麼您可以直接使用它修改該列表。

public boolean remove(ProductNode<E> data) { 
    if (isEmpty()) { 
     throw new NoSuchElementException(); 
    } 
    ProductNode<E> pre = data.prev; 
    ProductNode<E> next = data.next; 

    //First remove the nodes references to its neighbors. 
    data.prev = null; 
    data.next = null; 

    // Now check the neighbors and update their references 
    // to remove all references to the deleted node. 
    if (pre != null) pre.next = next; 
    if (next != null) next.prev = pre; 
    if (data == head) { //This checks the actual memory address. 
     head = next; 
    } 
    size--; 
} 

由於您已經擁有ProductNode,因此無需搜索該列表。你的search()函數已經爲你做了。因爲你已經擁有了只需要引用它的鄰居null的節點,那麼你只需要訪問鄰居(如果有的話),並讓它們的舊引用跳過被刪除的節點。

我注意到一些參考錯誤,其中刪除的節點沒有完全從列表中刪除,但我不會提及它們,因爲此刪除功能相當複雜。嘗試簡化刪除功能,然後看看你的結果是什麼。

如果向我們展示List_Products對象的結構,它也可能會有所幫助。

此外,您應該驗證您在UI中選擇的數據是否正確傳遞。這可能是一個UI錯誤。

+0

您說得對,如果刪除頭部,該怎麼辦? –

+0

我做了一個小的編輯來處理頭部的情況。再一次,因爲已經有了Node引用,所以很容易檢查頭對當前節點的內存地址,如果它們相同,則更新頭。 – MichaelBadgett

+0

如果我的解決方案爲您工作,請將我的答案標記爲已接受,如果不是,請讓我知道它沒有工作。謝謝! – MichaelBadgett