SHARE
TWEET

Untitled

a guest Jan 26th, 2020 77 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class ArrayBasedStack {
  2.   public Object[] stack;
  3.   public int size;
  4.  
  5.   /**
  6.    * The constructor of the ArrayBasedStack.
  7.    *
  8.    * @param capacity
  9.    *     Maximum number of items that can be stored in the stack.
  10.    */
  11.    public ArrayBasedStack(int capacity) {
  12.     stack = new Object[capacity];
  13.     size = 0;
  14.   }
  15.  
  16.   /**
  17.    * Push an item to the stack.
  18.    *
  19.    * @param o
  20.    *     Object that is pushed on the stack.
  21.    * @return the object, iff the object has been pushed to stack successfully.
  22.    * Returns null, if the object cannot be pushed to the stack.
  23.    */
  24.   public Object push(Object o) {
  25.     if(size == stack.length) {
  26.         return null;
  27.     }
  28.     stack[size++] = o;
  29.     return o;
  30.    
  31.   }
  32.  
  33.   /**
  34.    * Pops the first item from the stack.
  35.    *
  36.    * @return the object, iff the object has been popped from stack successfully. Null, if the stack is empty.
  37.    */
  38.   public Object pop() {
  39.       if(size == 0)
  40.           return null;
  41.       Object o = stack[size-1];
  42.       size--;
  43.       return o;
  44.   }
  45.  
  46.   /**
  47.    * Check the item on top of the stack, without removing it.
  48.    *
  49.    * @return the top object, iff the stack has an item. Null, if the stack is empty.
  50.    */
  51.   public Object peek() {
  52.     if(size == 0) {
  53.         return null;
  54.     }
  55.     return stack[size-1];
  56.   }
  57. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top