Linked List Operation


Suppose we have a linked list with $n$ elements (nodes) and we want to delete an element at a given index $k$. This means we remove the $k^{th}$ node from the list. After deletion we have $n - 1$ elements:

Example: we have a linked list with 4 nodes at indices 0, 1, 2, and 3.

We will delete the node at index 2:

Exercise Complete the implementation of delete which removes a node at the given index.

public void delete(int index) {
    // TODO Implement me!

Hint: Use the following visualization as guidance.

public void delete(int index) {
  Node<T> beforeTarget = head;
  for(int counter = 0; counter < index - 1; counter++) {
    beforeTarget =;
  } =;

Caution: the implementation above fails to account for edge cases and cases where index is invalid!