Java Reference
In-Depth Information
Notice that the second step can be accomplished by calling the method remove , as given in the pre-
vious segment.
What if node N is first in the chain? If we do not treat this situation separately, the previous steps
will replace the entry in the first node with itself. It will be easier to let this happen than to add logic
that asks whether node N is the first one.
Thus, we have the following pseudocode for the method remove :
Locate a node N that contains anEntry
if ( node N exists )
{
Replace the entry in node N with the entry in the first node
remove()
}
return true or false according to whether the operation succeeds
3.23
Removing a given entry, continued. The search to locate a node that contains a given entry is the
same one done by the method contains in Segment 3.17. Rather than repeating this code in the
method remove , we can place it into a new private method that both remove and contains can call.
The definition of this private method follows:
// Locates a given entry within this bag.
// Returns a reference to the node containing the entry, if located,
// or null otherwise.
private Node getReferenceTo(T anEntry)
{
boolean found = false ;
Node currentNode = firstNode;
while (!found && (currentNode != null ))
{
if (anEntry.equals(currentNode.data))
found = true ;
else
currentNode = currentNode.next;
} // end while
return currentNode;
} // end getReferenceTo
The pseudocode given in the previous segment for the method remove now translates into Java
as follows:
public boolean remove(T anEntry)
{
boolean result = false ;
Node nodeN = getReferenceTo(anEntry);
if (nodeN != null )
{
nodeN.data = firstNode.data; // replace located entry with entry
// in first node
remove();
// remove first node
result = true ;
} // end if
return result;
} // end remove
Search WWH ::




Custom Search