Java Reference
In-Depth Information
for (int i = 0; i < index; i++) {
current = current.next;
}
return current;
}
The following is a complete implementation of the
LinkedIntList
that includes
the methods we have just developed, along with the other basic operations that we
included in our first version of
ArrayIntList
. Notice that the private
nodeAt
method is used in three different methods (
get
,
add
at an index, and
remove
). Here
is the code:
1 // Class LinkedIntList can be used to store a list of integers.
2
3
public class
LinkedIntList {
4
private
ListNode front; // first value in the list
5
6 // post: constructs an empty list
7
public
LinkedIntList() {
8 front = null;
9 }
10
11 // post: returns the current number of elements in the list
12
public int
size() {
13
int
count = 0;
14 ListNode current = front;
15
while
(current != null) {
16 current = current.next;
17 count++;
18 }
19
return
count;
20 }
21
22 // pre : 0 <= index < size()
23 // post: returns the integer at the given index in the list
24
public int
get(
int
index) {
25
return
nodeAt(index).data;
26 }
27
28 // post: returns comma-separated, bracketed version of list
29
public
String toString() {
30
if
(front == null) {
31
return
"[]";
32 }
else
{
Search WWH ::
Custom Search