在手动链表实现中删除节点中的最后一个对象
Removing the last object in a node in a manual linked list implementation
我目前实现的链表删除操作只有在要删除的节点不在链表末尾时才有效。我需要前一个节点现在指向 null,而不是指向最后一个节点,以便将其删除。最后一个节点的删除操作不会抛出 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;
}
修改了最初的建议,先检查头节点,如果是要删除的头节点,则对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,而不是指向最后一个节点,以便将其删除。最后一个节点的删除操作不会抛出 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;
}
修改了最初的建议,先检查头节点,如果是要删除的头节点,则对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;
}