Как удалить элемент из отсортированного двусвязного списка? - PullRequest
0 голосов
/ 14 ноября 2018

У меня есть отсортированный двусвязный список, который всегда начинается с первого элемента как нулевого и заканчивается последним элементом как нулевым. Когда список пуст, он выглядит так: {null, null}. Когда я вставляю значения a, b, c, список выглядит следующим образом: {null, a, b, c, null}.

У меня есть метод removeFirst (), который должен удалить первый элемент из списка, и список должен выглядеть следующим образом: {null, b, c, null}. И удаленный элемент возвращается.

У меня также есть метод removeLast (), который удаляет последний элемент, поэтому список должен выглядеть следующим образом: {null, b, null}. И удаленный элемент возвращается.

Метод removeElement () должен удалить элемент из списка в любом месте и вернуть значение true. Если элемент отсутствует в списке, возвращается false.

Проблема с кодом, который у меня сейчас есть, состоит в том, что removeFirst () удаляет первый элемент из списка, который является нулевым. И у меня та же проблема с методом removeLast (), он также удаляет последний элемент в списке, который является нулевым. Но первый и последний элементы в списке всегда должны быть нулевыми и не должны быть удалены.

Метод removeElement () не удаляет элементы из списка. Я не вижу, что мне не хватает.

Вот мой код:

// removes the first item in the list and returns the string
public String removeFirst() {

    // if the list is empty
    if (this.size == 0) {
        throw new NoSuchElementException();
    }

    Node tempNode = first;

    // if there is only one item in the list
    if (first.next == null) {
        last = null;
    } else {
        first.next.previous = null;
        first = first.next;
    }

    size--;

    return tempNode.data;
}

// removes the last item in the list and returns the string
public String removeLast() {

    // if the list is empty
    if (this.size == 0) {
        throw new NoSuchElementException();
    }

    Node tempNode = last.previous;

    // if there is only one item in the list
    if (first.equals(last)) {
        first.previous = null;
        first.next = last;
        last.previous = first;
        last.next = null;

        tempNode.next = null;

    } else {
        last.previous.next = null;
        last = last.previous;
        tempNode.previous = null;
    }

    size--;

    return tempNode.data;
}

// removes an item from the list
public boolean removeElement(String element) {
    boolean removed = false;

    try {
        // if the first element in the list should be removed
        if (first.data.equals(element)) {
            // if there is only one item in the list
            if (first.equals(last)) {
                last = null;
                first = first.next;

            } else {
                first.next.previous = null;
                first = first.next;
            }

            size--;
            removed = true;

            // if the last item in the list should be deleted
        } else if (last.data.equals(element)) {
            last.previous.next = null;
            last = last.previous;

            size--;
            removed = true;

        } else {
            Node before = first;
            Node after = first.next;

            // as long as there are more elements in the list
            while (first.next != null) {
                if (after.data.compareTo(element) == 0) {

                    before.next = after.next;
                    after.next.previous = before.next;

                    size--;
                    removed = true;

                    break;
                }

                before = after;
                after = after.next;
            }

        }
    } catch (NullPointerException e) {

        removed = false;
    }

    return removed;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...