/*  File: StackList.java    Authors: Koffman & Wolz
 *  A stack class implemented as a linked list.
 *  Data field top references the top of the stack.
 *  Uses inner class ListNode
 */
public class StackList  {

   // Insert inner class ListNode here.
   private class ListNode {
     // Data fields
     Object info;
     ListNode link;

     // Methods
     // Constructors
     public ListNode() {};

     public ListNode(Object i) {info = i; link = null;}

     public ListNode(Object i, ListNode l) {
       info = i;
       link = l;
     }
   }
   // end ListNode

   // Data fields
   private ListNode top;         // reference to
                                  //   top of stack

   // Methods
   /* push - pushes an item onto a stack
      precondition : item is defined
      postcondition: item is at the top of the stack
   */
   public StackList() {
     top = null;
   }

   public void push(Object item) {
      //Allocate a new node, store item in it, and
      //  link it to old top of stack.
      top = new ListNode(item, top);
   }


   /* pop - pops an item from a stack
      precondition : stack is defined and is not empty
      postcondition: returns item at top of stack and
                     removes it from the stack. Old second
                     stack element is at top of stack.
   */
   public Object pop() {
       Object item = peek();   // Retrieve item at top

       //Remove old top of stack
       top = top.link;     // Link top to second element

       return item;        // Return data at old top
   }


   /* peek - retrieves an item from a stack
    * precondition : stack is defined and is not empty
    * postcondition: returns item at top of stack without
    *                removing it.
    */
   public Object peek() {
       if (isEmpty())
          throw new NullPointerException();
       return top.info;      //return top item
   }


   /* isEmpty - tests whether a stack is empty
    * precondition : none
    * postcondition: returns true if stack is empty;
    *                otherwise, returns false.
    */
    public boolean isEmpty() {
        return (top == null);
    }

} // class StackList

