Search code examples
javadata-structuresmethodslinked-listdoubly-linked-list

Cant delete node from doubly linked list


This is the method which I am trying to do... Its always printing "Nothing to delete1" even if name to delete exist.

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;

}

Solution

  • Your problem is in how you update the links between different nodes to remove a particular node from the linked list.

    current.setPrevious(current.getNext());
    

    Above statement will set the previous link of the current node to the node next to the current node; this is not correct.

    The above statement does the following operation:

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

    To remove the current node, you need to:

    1. Set the next of the previous node to point to the node next to the current node

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

      Basically, you want to do the following:

      |previous node| ---> |next node|
      
    2. Set the previous of the node, next to the current node, to point to the node previous to the current node

      current.getNext().setPrevious(current.getPrevious());
      

      Here, you want to do the following:

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

    After that, you can set the previous and next of the current node to null

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

    I would re-write your method as shown below:

    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;
    }