无法从双向链表中删除节点

Cant delete node from doubly linked list

这是我正在尝试做的方法...即使存在要删除的名称,它也总是打印“Nothing to delete1”。

public String deleteName(String name){
    Node current, previous;
   
    String a ="";
     current = start;
     previous = null;
     
      while(current != null && !current.getData().getName().equals(name)  ){
         current = current.getNext();
         a = "Nothing to delete1"; 
      }
      if(current == null){
         a = "Nothing to delete";
      }
      
     if(current.getData().equals(name)){
        a = "name deleted";
        current.setPrevious(current.getNext());
        current.setNext(null);
        
     }

  return a;

}

您的问题在于如何更新不同节点之间的 links 以从 linked 列表中删除特定节点。

current.setPrevious(current.getNext());

以上语句会将current节点的previouslink设置为current节点的下一个节点;这是不正确的。

以上语句做了如下操作:

|next node| <--- |current node|

要删除 current 节点,您需要:

  1. 设置前一个节点的next指向current节点的下一个节点

    current.getPrevious().setNext(current.getNext());
    

    基本上,您想执行以下操作:

    |previous node| ---> |next node|
    
  2. 设置current节点后节点的previous指向current节点

    之前的节点
    current.getNext().setPrevious(current.getPrevious());
    

    在这里,您想执行以下操作:

    |previous node| <--- |next node|
    

之后可以将current节点的previousnext设置为null

current.setNext(null);
current.setPrevious(null); 

我会重新编写您的方法,如下所示:

public String deleteName(String name){
   
    String result = "";
    Node current = start;
    Node previous = null;
     
    while(current != null && !current.getData().getName().equals(name)){
       current = current.getNext();
    }
      
    if(current == null){
       result = "Nothing to delete";
    } else {
       current.getPrevious().setNext(current.getNext());
       current.getNext().setPrevious(current.getPrevious());

       current.setNext(null);
       current.setPrevious(null); 
       
       result = "name deleted";
    }

    return result;
}