Java Reference
In-Depth Information
public int max() {
if (front == null) {
throw new IllegalStateException();
} else {
int maxValue = front.data;
ListNode current = front.next;
while (current != null) {
maxValue = Math.max(maxValue, current.data);
current = current.next;
}
return maxValue;
}
}
26. The four cases examined are the typical case in the “middle” of the list, inserting at
the back of the list, inserting at the front, and the empty list case.
27. A program takes the “inchworm approach” when an algorithm keeps track of two
linked node references, one for the previous node and one for the current node.
They are moved forward together over the list until they reach a particular posi-
tion. At that point, the previous reference is modified as appropriate. One advan-
tage of this approach is that you do not need to write complex chains of
dereferences such as current.next.data .
28. public int sum() {
int total = 0;
ListNode current = front;
while (current != null) {
total += current.data;
current = current.next;
}
return total;
}
public double average() {
if (front == null) {
return 0.0;
} else {
int total = 0;
int count = 0;
ListNode current = front;
while (current != null) {
total += current.data;
current = current.next;
count++;
}
Search WWH ::




Custom Search