What happens if we input a bunch of words, push them all onto a stack, and then, as we pop them off, display them?
So what will happen to the words when they're output? Try this on your own first:
Question #14.1.1: The words "Madam I'm Adam" were pushed one after the other onto a stack and then they were printed as they were popped from the stack. What would be printed?
Question #14.1.2: Now predict what will happen in general to any sequence of words.
The behavior of the program you are to write is as follows:
The program will create a new empty stack. It will prompt for and read in a file name from the keyboard and then will open that file for input. Words are read from the file and each is pushed onto the stack .When the end-of-file is reached, the file is closed. Words are then popped from the stack and displayed on the screen (or if you prefer, written to an output file) until the stack is empty.
The objects for this program are quite straightforward:
Description Type Kind Name the stack of words
the file name
the input stream
The operations are fairly straightforward as well. The following list omits the file operations, but you can look them up from previous labs.
Description Predefined? Name Library create a new stack yes
push a word onto the stack yes
test if stack is empty yes
get top value from stack yes
pop top value from stack yes
stack is like declaring a
list. Use the same syntax, but use "
stack" for the container. The other operations will be
methods invoked on
So we end up with this algorithm:
inFileName) and test that it opened properly.
inStreamis at the end-of-file, terminate the loop.
theStackis not empty:
theStackon the screen (followed by some whitespace).
Write the program, compile it, and execute it.
Compare your prediction with the actual outcome.
Question #14.1.3: How closely did your prediction match the actual outcome?
Question #14.1.4: How does LIFO explain the behavior you see from your program?