简体   繁体   English

在手动链接列表实现 (Java) 中删除节点中的最后一个 object

[英]Removing the last object in a Node in a manual Linked List implementation (Java)

My current implementation of the removal operation of linked lists only works when the Node to be removed is not at the end of the list.我当前对链表的删除操作的实现仅在要删除的节点不在列表末尾时才有效。 I need the previous Node to now point to null, instead of pointing to the last Node, in order for it to be deleted.我需要前一个节点现在指向 null,而不是指向最后一个节点,以便将其删除。 Instead of throwing a NullPointerException, the remove operation for the last Node just keeps the list as is.最后一个节点的删除操作不会抛出 NullPointerException,而是保持列表不变。 How would I change the else if condition to reflect this?我将如何更改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;
}

Modify your function like below, the use of prev variable to keep track of the node so that when you need to delete the last node, you correctly terminate the list.修改您的 function 如下所示,使用prev变量来跟踪节点,以便当您需要删除最后一个节点时,您可以正确终止列表。

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

    Node prev=head;
    
    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;
        }        
        prev = current;
        current = current.getNext();
    }
    if(current.getBook().equals(bookToRemove))
    {
        //last node is the one to remove
        //so set the last but one node to be terminating the list
        prev.setNext(null);
    }
    return bookToRemove;
}

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

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