Java has a library class Stack that provides a stack of Objects, with methods push to add an Object, pop to remove and return the most recently added Object, peek to return a reference to the most recently added Object without removing it, and empty to say whether the stack is empty or not. (This is called a legacy data structure in Java, meaning that it is old, to be replaced by a newer library classes, such as LinkedList.)
Here is a simpler, non-object-oriented version of the same code, without an interface and without a stack class. The implementation of the stack is woven into the code for the main method: here.
More complex and interesting source that checks intermingled parens and other brackets for balance was here, but I discovered that this is a recitation exercise for a week or two from now. Rats! (In case you already looked at it, my solution is quite different from the solution suggested in the recitation.)
Fill in code where the boldface wording appears in the following program (modeled after the 2nd item above), so that it will take the given string, push each character on the stack in order, and finally pop and print each character. Thus it prints the string in reverse order. (You shouldn't need any other classes for this.)
// CharStackMain: Use Java's library Stack class (legacy)
// Print a string in reverse order by pushing first on a stack
import java.util.*; // for the Stack class and the exception class
public class CharStackMain {
public static void main(String[] args) {
// string to use for data
String str = new String("The quick brown fox jumps over the lazy dog");
// create two stacks of Objects, s and t
// push chars from the string onto the stacks. Need wrappers.
// Can assign Character to Object, but not char to Object
for each char in the ith position of the string str, in order
extract the ith char, and wrap it in a Character object
push this object on each of the two stacks
}
// pop and print the first stack, using empty()
// method to terminate loop
while stack is not empty
pop and print the character
// pop and print 2nd stack, using EmptyStackException
// to terminate loop (not the preferred method)
while (true) {
try to pop and print the character
catch the exception if stack is empty
do what is necessary if exception caught
}
}
}
}
Output:
god yzal eht revo spmuj xof nworb kciuq ehT
god yzal eht revo spmuj xof nworb kciuq ehT