Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
obaibula opened this issue Apr 7, 2023 · 0 comments
Open

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

obaibula opened this issue Apr 7, 2023 · 0 comments

Comments

@obaibula
Copy link

obaibula commented Apr 7, 2023

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;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant