// Stack.java -- generic version of linked-list Stack from Lab 07

package lab13;

public class Stack<E> {

    private Node<E> topNode;
    private int itemCount;

    public Stack () {
        topNode = null;
        itemCount = 0;
    }

    public void push (E value) {
        topNode = new Node<E> (value, topNode);
        itemCount++;
    }
    
    public E pop () throws IllegalStateException {
        if (topNode == null) {
            throw new IllegalStateException ("Stack is empty");
        }
        Node<E> oldTopNode = topNode;
        topNode = topNode.next;
        itemCount--;
        return oldTopNode.value;
    }

    public E peek () throws IllegalStateException {
        if (topNode == null) {
            throw new IllegalStateException ("Stack is empty");
        }
        return topNode.value;
    }

    public boolean isEmpty () {
        return (itemCount == 0);
    }

    public int size () {
        return itemCount;
    }

    public void removeAll () {
        topNode = null;
        itemCount = 0;
    }
    
    public String toString () {
        Node<E> curNode = topNode;
        String s = "Stack: ";
        while (curNode != null) {
            s += (curNode.value).toString() + " ";
        }
        return s.trim();
    }

}

class Node<E> {
    E value;
    Node<E> next;

    public Node (E value, Node<E> next) {
        this.value = value;
        this.next = next;
    }
}
