首页 > 解决方案 > Java双向链表删除方法

问题描述

我的问题是我的删除方法没有删除我要删除的节点并给我一个无限循环。

public void delete(String name){
      Node current = head;
      boolean checker = false;
         while(current != null && current.name != name && checker != true){
            try{
               if(current.name.equals(name)){
                  Node p = current.previous;
                  Node q = current.next;
/*The code can somehow get through only above this line, below here its not anymore*/
                  p.next = q;
                  q.previous = p;
                  System.out.println("Item successfully deleted.");
                  checker = true;
               }else if(!current.name.equals(name) && current == tail){
                  System.out.println("Item not found.");
               }
               current = current.next;
            } catch(NullPointerException e){}          
         }
   }

我在这里寻求有关我的问题的提示或提示(抱歉我的英语不好)

标签: javaoopdoubly-linked-list

解决方案


您正在检查您是否已到达列表的末尾,current == tail但没有突破它。您可以breakelse if.

除此之外,您还==用于比较字符串。我不确定你为什么在那里添加它并且可以将其删除。此外,您必须(几乎总是)永远不要捕获 NullPointerException。


推荐阅读