繁体   English   中英

从单个链表Java中删除字符串节点

[英]Remove String node from single linked list java

您好,我正在学习单链列表,并且正在使用Java书籍中的示例,我正在尝试删除具有字符串值的节点。 我已经编码了,但是我没有删除任何东西,任何人都可以给我任何建议吗? 我已经很沮丧,因为我不知道我在做什么错。 谢谢。

   public class LinkedStringLog implements StringLogInterface {
  protected LLStringNode log; // reference to first node of linked 
                              // list that holds the StringLog strings
  protected String name;      // name of this StringLog

  public LinkedStringLog(String name)
  // Instantiates and returns a reference to an empty StringLog object 
  // with name "name".
  {
    log = null;
    this.name = name;
  }
  public void remove(String element){
  LLStringNode currentNode;
  LLStringNode temporal;
  currentNode = log;
  temporal = currentNode.getLink();

  if(element.equalsIgnoreCase(currentNode.getInfo())){
      log = currentNode.getLink();

  } 

 while(currentNode!=null){
      if(element.equalsIgnoreCase(currentNode.getInfo())){
          temporal.setLink(currentNode.getLink());
      }
      else{
          currentNode.getLink();
          temporal = currentNode;
      }

  }

我猜您正在进入无限循环,因为您没有在while循环中更新currentNode变量。

您可能想要这样的东西:

while(currentNode!=null){
      if(element.equalsIgnoreCase(currentNode.getInfo())){
          //don't you want to update the link of the node before currentNode here?
      }
      else{
          currentNode = temporal; //update currentNode variable
          temporal = currentNode.getLink(); //update temporal variable
      }

  }

您似乎有很多错误。

主要问题之一是,遍历链接列表时您未能维护prevNode引用,因此无法将列表中的所有项目保持链接在一起。

另外,您在哪里将log设置为链接列表的首页?

无论如何,此版本的remove可能会更好(只要log实际上是非null的):

     public void remove(String element) {
         if (log == null) {
             return;
         }
         LLStringNode currentNode = log;
         LLStringNode prevNode = null;

         while (currentNode != null) {
             LLStringNode nextNode = currentNode.getLink();
             if (element.equalsIgnoreCase(currentNode.getInfo())) {
                 if (currentNode.equals(log)) {
                     log = nextNode;
                 }
                 if (prevNode != null) {
                     prevNode.setLink(nextNode);
                 }
             } else {
                 prevNode = currentNode;
             }
             currentNode = nextNode;
         }
     }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM