Java Reference
In-Depth Information
Display 15.8
A Generic Linked List Class
(part 2 of 3)
45
/**
46
Returns the number of nodes in the list.
47
*/
48
public
int
size( )
49
{
50
int
count = 0;
51
Node<T> position = head;
52
while
(position !=
null
)
53
{
54
count++;
55
position = position.link;
56
}
57
return
count;
58
}
59
public
boolean
contains(T item)
60
{
61
return
(find(item) !=
null
);
62
}
63
/**
64
Finds the first node containing the target item, and returns a
65
reference to that node. If target is not in the list, null is returned.
66
*/
67
private
Node<T> find(T target)
68
{
69
Node<T> position = head;
Type
T
must have well-defined
equals
for this method to work.
70
T itemAtPosition;
71
while
(position !=
null
)
72
{
73
itemAtPosition = position.data;
74
if
(itemAtPosition.equals(target))
75
return
position;
76
position = position.link;
77
}
78
return
null
;
//target was not found
79
}
80
/**
81
Finds the first node containing the target and returns a reference
82
to the data in that node. If target is not in the list, null is returned.
83
*/
84
public
T findData(T target)
85
{
86
return
find(target).data;
87
}
(continued)