简体   繁体   中英

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. Instead of throwing a NullPointerException, the remove operation for the last Node just keeps the list as is. How would I change the else if condition to reflect this?

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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