Java Reference
In-Depth Information
1
// Simple print method
2
public static <AnyType> void printList( LinkedList<AnyType> theList )
3
{
4
if( theList.isEmpty( ) )
5
System.out.print( "Empty list" );
6
else
7
{
8
LinkedListIterator<AnyType> itr = theList.first( );
9
for( ; itr.isValid( ); itr.advance( ) )
10
System.out.print( itr.retrieve( ) + " " );
11
}
12
13
System.out.println( );
14
}
figure 17.10
A method for printing the contents of a
LinkedList
position and list actually are separate objects. Moreover, it allows for a list
to be accessed in several places simultaneously. For instance, to remove a
sublist from a list, we can easily add a
remove
operation to the list class that
uses two iterators to specify the starting and ending points of the sublist to
be removed. Without the iterator class, this action would be more difficult to
express.
We can now implement the remaining
LinkedList
methods. First is
find
,
shown in Figure 17.11, which returns the position in the list of some element.
Line 10 takes advantage of the fact that the
and
(
&&
) operation is short-circuited:
Short-circuiting is
used in the
find
routine at line 10
and in the similar
part of the
remove
routine.
1
/**
2
* Return iterator corresponding to the first node containing x.
3
* @param x the item to search for.
4
* @return an iterator; iterator isPastEnd if item is not found.
5
*/
6
public LinkedListIterator<AnyType> find( AnyType x )
7
{
8
ListNode<AnyType> itr = header.next;
9
10
while( itr != null && !itr.element.equals( x ) )
11
itr = itr.next;
12
13
return new LinkedListIterator<AnyType>( itr );
14
}
figure 17.11
The
find
routine for the
LinkedList
class
Search WWH ::
Custom Search