/**
   The LinkedStack class implements the Stack interface by means of
   a singly linked list without dummy nodes.
 
   @author      Franck van Breugel
   @version     1.1    May 10, 2000
   @see Node
*/
public class LinkedStack implements Stack 
{
    private Node top; // reference to top node of this stack
    private int size; // size of this stack

    /** Constructs an empty LinkedStack. */
    public LinkedStack() 
    {
        top = null;
        size = 0;
    }

    public int size() 
    {
        return size;
    }

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

    public Object top() throws StackEmptyException 
    {
        if (isEmpty()) 
        {
            throw new StackEmptyException("Stack is empty.");
        }
        return top.getElement();
    }

    public void push(Object element) 
    {
        Node node = new Node(element, top);
        top = node;
        size++;
    }

    public Object pop() throws StackEmptyException 
    {
        if (isEmpty()) 
        {
            throw new StackEmptyException("Stack is empty.");
        }
        Object element = top.getElement();
        top = top.getNext();
        size--;
        return element;
    }    

    /**
       Returns a string representation of this stack.
      
       @return A string representation of this stack.
     */
    public String toString() 
    {
        String rep = "";
        for (Node n = top; n != null; n = n.getNext()) 
        {
        /* rep = element contained in top + "\n" + ... + element contained in node before node n + "\n" */
            rep += n.getElement().toString();
            rep += "\n";
        }
        return rep;
    }
}
