I have a pretty basic question here. I am implementing a few operations on a linked list as an exercise. One such operation is removal:
/**
* Removes the element at index.
* @param index
* @throws IndexOutOfBoundsException If index is greater than the list's length.
*/
public void remove(int index) throws IndexOutOfBoundsException;
The class's only instance variable:
private Node<T> first;
Node class:
public class Node<T> {
public T datum;
public Node<T> next;
public Node(T datum) {
this.datum = datum;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((datum == null) ? 0 : datum.hashCode());
result = prime * result + ((next == null) ? 0 : next.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node<T> other = (Node<T>) obj;
if (datum == null) {
if (other.datum != null)
return false;
} else if (!datum.equals(other.datum))
return false;
if (next == null) {
if (other.next != null)
return false;
} else if (!next.equals(other.next))
return false;
return true;
}
}
Here is my implementation of remove()
:
@Override
public void remove(final int index) throws IndexOutOfBoundsException {
if (null == first) {
throw new IndexOutOfBoundsException();
}
Node<T> current = first;
int nodesExamined = 0;
if (0 == index) {
first = first.next;
return;
}
while (null != current) {
if (nodesExamined + 1 == index) {
current.next = null == current.next ? null : current.next.next;
return;
}
nodesExamined++;
current = current.next;
}
throw new IndexOutOfBoundsException();
}
It passes a few tests, but probably has a few bugs left. Is the overall approach correct, though? It feels like I'm over-complicating.