I am implementing some basic data structures to freshen up my memory and I wanted my DoubleLinkedList
remove method to be reviewed. I feel like it has extra checks but I could not think of another way to implement.
My implementation holds both the head
and the tail
of the list making things a bit more complex.
remove
method:
public void remove(T data) {
if (isEmpty()) {
throw new NoSuchElementException();
}
for (Node<T> current = this.head; current != null; current = current.getNext()) {
if (current.getData().equals(data)) {
Node<T> previous = current.getPrevious();
Node<T> next = current.getNext();
if (this.size == 1) { // At head with size == 1
this.head = this.tail = null;
} else if (previous == null) { // At head with size > 1
this.head = next;
next.setPrevious(previous);
} else if (next == null) { // At tail
previous.setNext(next);
this.tail = previous;
} else { // Rest of cases
previous.setNext(next);
next.setPrevious(previous);
}
this.size--;
return;
}
}
throw new NoSuchElementException();
}
remove
. 2. Instead, they return the removed element, if any. 3. I'm unsure, ifNoSuchElementException
is appropriate, if you really want to throw. 4. Using a cycle with a dummy element would reduce all four cases to one, but I'm not claiming you should waste the memory for it. \$\endgroup\$NoSuchElementException
that is why I did it like that. \$\endgroup\$