【发布时间】: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