CMPSCI 187: Programming With Data Structures

David Mix Barrington

Fall, 2011

Discussion Assignment #1: Playing With Stacks

14 September 2011

Consider a seaport like the one pictured on the cover of Lewis & Chase. We have containers that are offloaded from ships and need to be sent out on trucks or trains, and the job of the seaport is to get the right containers to the right place. Containers are outwardly identical and labeled, much like the data objects in many of our applications.

Today we will look at a simplified form of the more general problem of disbursing the containers. We imagine that a sequence of containers comes off the ship, eahc container labeled by a letter. In our first example, the containers are labeled A-M-H-E-R-S-T, with the A first and the T last. They need to go out in alphabetical order, in this case in the order A-E-H-M-R-S-T.

We have two places to store a container if we can't send it out immediately. There is a buffer that can hold one container, and a stack that can hold any number. We push new containers onto the stack, and we can pop a container off, but only the last container that was pushed. (We may if we like think of the buffer as a stack of size 1.) Containers may never be put back onto the ship, or retrieved once they have been output.

We will see on the board how to deal with the sequence A-M-H-E-R-S-T with just the stack, not needing the buffer. Then we'll see that the sequence B-E-A-S-T can be done with both stack and buffer. Note that both solutions are offline, meaning that we know the entire input before we have to make any decisions.

Here are your exercises. Each team of students should submit one answer, probably after working it out on scratch paper.

  1. Show how to deal with the sequence Z-E-B-R-A, using both stack and buffer. (In the 9:05 discussion I mistakenly did Z-E-B-R-A on the board, so those students did B-E-A-S-T.

  2. Show how to deal with the sequence C-A-M-B-R-I-D-G-E, using both stack and buffer.

  3. Do one of the following: (a) Explain how any possible sequence can be processed with the stack and one buffer, or (b) find a sequence that cannot be processed with the stack and one buffer, and write a convincing argument that it cannot.

  4. The sequences B-E-A-S-T, Z-E-B-R-A, and C-A-M-B-R-I-D-G-E each cannot be done with the stack alone. Can you find a rule to determine, given a sequence, whether it can be done with the stack alone?

    Last modified 17 September 2011