Linked list 双链表java删除
删除多个节点时出现问题 如果选择如下节点,则可以删除它们: 但如果我这样做,我不能删除它们: 我的代码:Linked list 双链表java删除,linked-list,Linked List,删除多个节点时出现问题 如果选择如下节点,则可以删除它们: 但如果我这样做,我不能删除它们: 我的代码: public boolean remove(ProductNode<E> data) { if (isEmpty()) { throw new NoSuchElementException(); } for (ProductNode<E> current = this.head; current != null; c
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;
}
删除:
for(Tab_Product p : remove_list){
List_Products.list_products.remove(p);
}
删除函数(ProductNode data)有点复杂,可能会影响代码删除多个节点的能力。对于此移除函数,您不需要遍历整个数据集。如果已经有对节点的引用,则可以直接使用它修改列表
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数据){
if(isEmpty()){
抛出新的NoTouchElementException();
}
ProductNode pre=data.prev;
ProductNode next=data.next;
//首先删除对其邻居的节点引用。
data.prev=null;
data.next=null;
//现在检查邻居并更新他们的引用
//删除对已删除节点的所有引用。
如果(pre!=null)pre.next=next;
如果(next!=null)next.prev=pre;
如果(data==head){//,则检查实际内存地址。
头=下一个;
}
大小--;
}
由于您已经拥有ProductNode,因此不需要搜索列表。您的search()函数已经在为您执行此操作。由于您已经拥有该节点,因此只需将其对其邻居的引用设为null,然后只需访问邻居(如果有),并使其旧引用跳过已删除的节点
我注意到一些引用错误,其中删除的节点没有从列表中完全删除,但我不会提及它们,因为这个删除函数相当复杂。尝试简化delete函数,然后查看结果
如果您向我们展示List_Products对象的结构,也可能会有所帮助
此外,您应该验证您在UI中选择的数据是否正确传递。这可能是一个UI错误。您是否尝试过使用调试器单步执行代码?这可能会更清楚发生了什么,以及何时(如果问题发生在删除相邻节点时,或者删除列表中的第一个节点时,等等),我做了一个小编辑来处理头部情况。再一次,由于您已经有了节点引用,因此很容易对照当前节点检查磁头的内存地址,如果它们相同,则更新磁头。如果我的解决方案对您有效,请将我的答案标记为已接受,如果没有,请让我知道它不起作用。谢谢
for(Tab_Product p : remove_list){
List_Products.list_products.remove(p);
}
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--;
}