Java Reference
In-Depth Information
Display 15.3
A Linked List Class
(part 2 of 2)
39
while (position != null)
This last node is indicated
by the
link
field being equal
to
null
.
40
{
41
count++;
42
position = position.getLink( );
43
}
44
return
count;
45
}
46
public
boolean
contains(String item)
47
{
48
return
(find(item) !=
null
);
49
}
50
/**
51
Finds the first node containing the target item, and returns a
52
reference to that node. If target is not in the list, null is returned.
53
*/
54
private
Node1 find(String target)
55
{
56
Node1 position = head;
57
String itemAtPosition;
58
while
(position != null)
59
{
60
itemAtPosition = position.getItem( );
61
if
(itemAtPosition.equals(target))
62
return
position;
63
position = position.getLink( );
This is the way you
traverse an entire
linked list.
64
}
65
return
null
;
//target was not found
66
}
67
public
void
outputList( )
68
{
69
Node1 position = head;
70
while
(position != null)
71
{
72
System.out.println(position.getItem( ) + " "
73
+ position.getCount( ));
74
position = position.getLink( );
75
}
76
}
77
}
78