/**
* Stack linked list class makes use of composition in
* that it "has-a" reference to a LinkedList class object
* that it creates in the constructor.
* The Stack class then "delegates" the Stack method calls
* to the appropriate LinkedList methods.
* @author Suzanne Balik, 16 Oct 2001,
* based on code in Java How to Program by Deitel & Deitel
*/
public class Stack {
private LinkedList list;
public Stack() {
list = new LinkedList();
}
public boolean isEmpty() {
return list.isEmpty();
}
public void push(int info) {
list.addToFront(info);
}
public int pop() throws EmptyListException {
if (isEmpty())
throw new EmptyListException("Stack is empty!");
else
return list.removeFromFront();
}
public String toString() {
return list.toString();
}
public static void main(String[] args) {
Stack stack = new Stack();
//Catch EmptyListException's
try {
System.out.println("Stack empty? " + stack.isEmpty());
stack.push(5);
stack.push(9);
stack.push(4);
stack.push(8);
System.out.println("stack empty? " + stack.isEmpty());
System.out.println(stack);
while (!stack.isEmpty()) {
System.out.println("Popped from stack: " +
stack.pop());
System.out.println(stack);
}
//See what happens if we pop empty stack
stack.pop();
}
catch (EmptyListException e) {
System.err.println(e);
}
//See what happens if we pop empty stack without
//catching exception
stack.pop();
}
}