Skip to content

2-2-4-linked-list, remove tests accept the broken code #167

Open
@obaibula

Description

@obaibula

The next broken code is accepted:

@Override
    public T remove(int index) {
        checkIndex(index, size);

        if (index == 0) {
            return removeHead();
        } else if (index == size - 1) {
            return removeTail();
        } else {
            return removeInBetween(index);
        }
    }

    private T removeInBetween(int index) {
        Node<T> previous = getNodeByIndex(index - 1);
        T removed = previous.next.element;
        previous.next = previous.next.next;

        size--;

        return removed;
    }

    private T removeTail() {
        T removed = tail.element;

        Node<T> preTail = getNodeByIndex(size - 2);
        preTail.next = null;
        tail = preTail;

        size--;
        return removed;
    }

    private T removeHead() {
        T removed = head.element;
        head = head.next;
        size--;
        return removed;
    }

Please consider the following example:

LinkedList<Integer> list = LinkedList.of(10);

        System.out.println(list.remove(0));

        System.out.println(list.size());
        System.out.println(list.getLast());

In this example, we can still get the "last" element even if size == 0.

It's necessary to reassign tail, as shown below:

private T removeHead() {
        T removed = head.element;
        head = head.next;
        size--;

        if(head == null){
            tail = null;
        }

        return removed;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions