Frage

I'm currently writing code on Singly Linked Lists. How would I remove an element after the object passed in as the parameter in a single linked list?

Here is my method to remove the last element of the list

public Object removeLast() throws EmptyListException {

    if (head == null) throw new EmptyListException();

    Object o;

    // If there is only one element, we need to modify the head of the list
    if (head.next == null) {
        o = head.content;
        head.content = null;
        head = null;
        return o;
    }

    Node crt = head;
    while (crt.next.next != null)
        crt = crt.next;

    o = crt.next.content;

    // Remove all references that are not needed
    crt.next.content = null;
    crt.next = null;

    return o;
}
War es hilfreich?

Lösung

Here is the pseudo-code algorithm. It's up to you to translate it into Java, if you don't mind ;)

removeAfter(elem):
    if head == null -> error // empty list

    current = head
    while current != null && current != elem:
        current = current.next
    ;

    if current == null -> error // elem not found
    if current.next == null -> error // no more item after elem

    content = curent.next.content
    current.next = current.next.next
    return content
;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top