Skip to content

Stacks

As mentioned in the introduction a stack would comprise of a collection of objects with various operations related to maintaining the collection. As an example a stack of strings could have the following operations associated.

//psuedo code
public class StackOfStrings()
//create an empty stack
StackOfStrings()
//insert a new string into stack
void push(String item)
//remove eand return the string most recently added
String pop()
// is the stack empty?
boolean isEmpty()
// number of strings in the stack
int size()

Lets write a simple client that takes some simple strings on standard input and some pop commands which are indicated with -

public static void main(String[] args){
StackOfStrings stack = new StackOfStrings();
while(!StdIn.isEmpty()){
String s = StdIn.readString();
if(s.equals("-")) StdOut.print(stack.pop());
else stack.push(s);
}
}