2017-05-25 145 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