Scores, consisting of an array theScores,
where each entry is a reference to a List object. The
idea is that the
array entry at index i is a linked list of the names of
all students who got a grade of i. The array indices run
from 0 to 100.
This example uses a slightly modified version of the circular, doubly linked list with a sentinel. You can find the class in List.java. There are only minor differences between these linked lists and those that we previously saw. The first two matter for this program, and the last two will be used in the next program we look at.
Element::print() is overloaded - one version takes
a PrintWriter object and writes to a file.
List::print() is overloaded. The version that does
not take an PrintWriter as a parameter prints to
System.out. The other version takes a
PrintWriter object
as a parameter.
firstOf() makes the current element be the first
one on the list (sentinel.next).
getCurrentData() returns a copy of the string
in the current element.
PrintWriter object
would just pass System.out to the versions that do.
Unfortunately System.out is of type PrintStream,
rather than PrintWriter,
so this will not work unless we learn a new way of opening a file for
writing.
Observe how the member functions for Scores in Scores.java
make simple calls to the linked list member functions for the
List objects in the appropriate array slots.
Try running this program. You can load scores in by using the command "l" and loading scores from the file Student Scores. To see that error handling works, load scores from the file Student Scores bad
Not surprisingly, the runtime stacks that you drew several weeks back are examples of a stack. Calling a method pushes a new stack frame, and returning from a method call pops the top stack frame.
Push, pop, and isEmpty are the "traditional" stack operations. With the push and pop operations, stacks are "last-in, first-out", or "LIFO". The print method, though nontraditional, is helpful to have in a demonstration program.
We can easily use a linked list as a stack. The class Stack
is in Stack.java. The only private
data is a List object. The functions push() and
pop() are both extraordinarily simple, as are the
functions isEmpty() and print().
You can test the stack code with the driver program StackTest.java.
A queue is defined by the following operations:
We can easily use a linked list as a queue, as the class
Queue does in Queue.java.
You can test this code with QueueTest.java.
A linked list makes a fine dequeue, as the class DEQueue
does in Dequeue.java.
You can test this code with DequeueTest.java.