Along with its award-winning Southern roadhouse cuisine, Bub's Bar-B-Q in
Sunderland has an excellent free jukebox. If you want to browse the songs
available, and find their numbers to punch in, you can only look at one page
of songs at a time. There are buttons allowing you to flip pages to the left
or the right, to make a different page visible.
The set of pages to the left and the set to the right are each in effect a
stack, since only the top page is accessible. With the whole set of pages
stored between the two stacks, we can access any page. We'll use a similar
pair of stacks to revisit the container sorting problem from Discussion #1.
And this time we will both write actual Java code and solve the problem
online, meaning that we deal with each container when we unload it,
without knowing anything about the others still on the ship.
Again we have a sequence of containers coming off the ship, and they need to
be sent out in alphabetical order. In Java, each container is an object of
type Container
and the Container
class has a method
public char getLabel( )
that returns a one-character label. (We
don't really care what characters are used -- the only requirement is that the
labels on the containers that are sent out come in the correct order according
to the <
operator on char
primitives.
We will use two Stack<Container>
objects named left
and right
. Remember that the Stack
class
has methods push
, pop
, peek
,
isEmpty
, and size
. You may also use one
internal variable of type Container
, to represent the holding
area where containers sit when they are just off the boat, and any number of
variables of type char
. You are writing a method for the
Seaport
class, which also already has the following three
methods:
public boolean hasMore( )
, which tells whether there are more Containers to unload,
public Container unload( )
, which returns the next Container
from the ship, and
public void sendOut (Container c)
, which sends out Container
c to the train.
Assume that the two Stack<Container>
objects
left
and right
have been created and are empty.
Write a method public void processShip( )
(in the Seaport
class) that has the following
side effect: After it is run, hasMore( )
is false and all the
Containers that were unloaded have been sent out, in order of their labls.
You may find it useful to write auxiliary methods to shift a container from the right stack to the left stack, or vice versal
Last modified 21 September 2011