简体   繁体   中英

Delete last element in singleLinked List

I am making a simple linked list and I'm trying to implement a method that allows me to delete the last node of the linked list. At some point, my method is wrong and I'm not sure where the error is and how to fix it. Here is the code!

public Nodo deleteEnd() {

    Nodo aux;
    if (head == null) {
        throw new NoSuchElementException("Element cant be deleted");

    } else {

        aux = head;

        while (aux.next.next != null) {
            aux = aux.next;
        }

        size--;
    }
    return aux;
}

You need to assign the next of the last but not least node to null :

if(head.next == null) {
    // head is last!
    head = null;
    size = 0;
} else {
    previous = head;
    current = head.next;
    // while current is not last, keep going
    while(current.next != null) {
       previous = current;
       current = current.next;
    }
    // current is now on last!
    previous.next = null;
    size--;
}

try reducing one .next :

    while (aux.next != null) {
        aux = aux.next;
    }
public Nodo deleteEnd() {
    if (head == null) {
        throw new NoSuchElementException("Element can't be deleted");
    }
    Nodo current = head;
    Nodo next = current.next;

    // Check if there is only the head element.
    if ( next == null )
    {
        size--;
        head = null;
        return current;
    }

    // Skip to the end.
    while (next.next != null) {
        current = next;
        next = next.next;
    }

    // Break the link to the next element.
    current.next = null;
    size--;
    return next;
}

Add

aux.next = null;

after the while loop - then there will be no reference to the last element.

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