/*  Stack Linked-List class
 *  
 *  Class Name:     StackLi
 *  Description:    Linked-list-based implementation of the stack 
 *  Author:         Ng Woon Liam
 *  Language:       Java
 *  Date:           10/1/2001
 *       
 *  Public Methods: isEmpty()       Return true if empty; else false
 *                  top()           Return most recently inserted item
 *                  pop()           Remove most recently inserted item
 *                  topAndPop()     Return and remove most recent item      
 *                  push()          Insert x
 *                  makeEmpty()     Remove all items
 */

public class StackLi implements Stack
{
    /**
     * Construct the stack.
     */
    public StackLi( )
    {
        topOfStack = null;
    }

    public boolean isEmpty( )
    {
        return topOfStack == null;
    }

    public void makeEmpty( )
    {
        topOfStack = null;
    }

    public Object top( ) throws Exception
    {
        if( isEmpty( ) )
            throw new Exception( "Stack top" );
        return topOfStack.element;
    }

    public void pop( ) throws Exception
    {
        if( isEmpty( ) )
            throw new Exception( "Stack pop" );
        topOfStack = topOfStack.next;
    }

    public Object topAndPop( ) throws Exception
    {
        if( isEmpty( ) )
            throw new Exception( "Stack topAndPop" );

        Object topItem = topOfStack.element;
        topOfStack = topOfStack.next;
        return topItem;
    }

    public void push( Object x )
    {
        topOfStack = new ListNode( x, topOfStack );
    }

    private ListNode topOfStack;
}
