// Arup Guha
// 6/30/04
// Stack Example for 2004 BCHSI

import java.io.*;

public class stack {

  private int[] values; // Stores the values.
  private int top; // Stores the index to the top of the stack object.

  // Constants used in the class.
  final static int DEFAULT_SIZE = 10;
  final static int EMPTY_STACK = -1;

  // Creates a new stack with a DEFAULT_SIZE capacity.
  public stack() {
    values = new int[DEFAULT_SIZE];
    top = 0;
  }

  // Creates a new stack with a size capacity.
  public stack(int size) {
    values = new int[size];
    top = 0;
  }

  // Pushes n onto the current stack object. The array storing the stack
  // is expanded if necessary.
  public void push(int n) {

    // Take care of the regular case where there's room left.
    if (top < values.length) {
      values[top] = n;
      top++;
    }

    // The case where the array needs to be expanded.
    else {

      // Create a temporary array of adequate size.
      int[] temp = new int[2*values.length];

      // Copy all the values into the temporary array.
      for (int i=0; i<values.length; i++)
        temp[i] = values[i];

      // Push the new value.
      temp[values.length] = n;
      top++;

      values = temp; // Reassign values to this new array.
    }
  }

  // Pops an element off the top of the stack and returns it. If no such
  // element exists, EMPTY_STACK will be returned.
  public int pop() {

    // Empty stack case.
    if (top == 0)
      return EMPTY_STACK;

    // Save the value to be popped, adjust top, and return the value.
    else {
      int temp = values[top-1];
      top--;
      return temp;
    }
  }

  // Returns the element at the top of the current stack object without
  // popping that element off the stack.
  public int top() {
    if (top == 0)
      return EMPTY_STACK;
    else
      return values[top];
  }

  // Returns true if and only if the current stack object is empty.
  public boolean empty() {
    return (top == 0);
  }

  // Returns true if and only if the current stack object is full.
  public boolean full() {
    return (top == values.length);
  }

  // Runs a very simple test of using a single stack object.
  public static void main(String[] args) {

    // Create a new stack and push three elements successively.
    stack s = new stack(3); 
    s.push(4);
    s.push(8);
    s.push(3);
 
    // Pop one element and print it out.
    System.out.println("Popping "+s.pop()+" off the stack.");

    // Push three more elements onto the stack.
    s.push(6);
    s.push(9);
    s.push(1);

    // Print these out as well.
    for (int i=0; i<5; i++)
      System.out.println("Popping "+s.pop()+" off the stack.");

  }
}
