public void remove(DataElement deleteItem)
{
if ( first == null )
{
// List empty, report it as an error
System.
err.
println("Cannot delete from an empty list.");
}
else
{
// So we know the list is not empty.
if ( first.data.equals(deleteItem) ) {
// The item we wish to delete is the first element
// of the list, simply move head of the list to the
// next element in the list.
first = first.link;
if ( first == null ) {
// There was only one element in the list,
// so make the list empty
last = null;
}
count--;
}
else
{
// Okay so we have to search the list for the item
// we wish to delete.
boolean found = false; // assume worst case
// We know it’s not the first element of the list,
// so lets start looking from the second element.
Node current = first.link;
// In order to remove the node we need to keep track
// of the node which proceeds the current node so
// we can modify its link correctly.
// As we are staring with the second node,
// that must be the first node.
Node previous = first;
// While we have not found the node, and we have not
// reached the end of the list.
while ( current != null && ! found )
{
if ( current.data.equals(deleteItem) )
{
// we have found our target
found = true;
}
else
{
// keep looking
previous = current;
current = current.link;
}
}
// Did we find the blasted thing
if ( found )
{
// Yes, the remove it !
// Modify the link on the previous node to refer
// to the next node, skipping the current node
// all together.
previous.link = current.link;
// If it was the last node, make the previous
// node the last node.
if ( last == current )
{
last = previous;
}
count--;
}
else
{
// Target node was not found !
// Report an error to the standard error output
System.
out.
println("Item to be deleted is "
+ "not in the list.");
}
}
// We really should invoke the garbage collector,
// but it’s not worth it for a single object.
}
}