【问题标题】:Removing the last object in a node in a manual linked list implementation在手动链表实现中删除节点中的最后一个对象
【发布时间】:2022-01-24 03:14:07
【问题描述】:

我目前对链表的删除操作的实现只有在要删除的节点不在链表末尾时才有效。我需要前一个节点现在指向空,而不是指向最后一个节点,以便将其删除。最后一个节点的删除操作不会抛出 NullPointerException,而是保持列表不变。我将如何更改 else if 条件以反映这一点?

public Book remove(Book bookToRemove){

    Node current = head; //each Node stores a Book

    if(isEmpty()){
        System.out.println("No books to remove!");
    }
    
    //what happens if the next next one is null?
    while(current.getNext() != null && !isEmpty()){
        if(current.getNext().getBook().equals(bookToRemove)){
            Node temp = current.getNext();
            current.setNext(temp.getNext());
            return bookToRemove;
        }

        
        else if(current.getNext() == null){ //
            //if the next node is null, it cannot be removed, or the previous node will have nothing to point to
            current.setNext(null);
            return bookToRemove;
        }

        current = current.getNext();
    }

    return bookToRemove;
}

【问题讨论】:

  • 你应该先检查else的情况,检查是否current.getNext() == null。这避免了 NPE。

标签: java linked-list


【解决方案1】:

修改了最初的建议,首先检查头节点,如果是要删除的头节点,则更改为head并退出该功能。流程的其余部分将负责删除列表中的任何其他位置。

public Book remove(Book bookToRemove)
{
    Node current = head; //each Node stores a Book

    if(isEmpty())
    {
        System.out.println("No books to remove!");
        return bookToRemove;   //no need to continue
    }

    if(current.getBook().equals(bookToRemove))
    {
      //found in head itself, make new head and exit
      head = current.getNext();
      return bookToRemove;
    }
    while(current.getNext() != null && !isEmpty())
    {
        if(current.getNext().getBook().equals(bookToRemove))
        {
            Node temp = current.getNext();
            current.setNext(temp.getNext());
            return bookToRemove;
        }        
        current = current.getNext();
    }
    return bookToRemove;
}

【讨论】:

  • 我理解这个逻辑,其中前一个节点需要将下一个节点设置为 null 才能删除当前节点,但是在测试此代码后,列表保持不变而不删除给定节点
  • 用少量书籍对象填写您的列表并逐步执行删除功能,然后您可以找到问题所在。还必须检查调用此函数的位置是否正确。
  • 上面的sn-p没有检查第一个节点,需要做。
  • 我已经修改了代码,首先检查头节点,如果不是要删除的节点,则检查列表的其余部分。不需要prev 节点。使用此更新后的功能并删除一个节点,然后打印列表并检查您的节点是否已删除,它应该可以工作。
猜你喜欢
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
相关资源
最近更新 更多