SHARE
TWEET

Untitled

a guest Jun 18th, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package io.phydesmith.stack;
  2.  
  3. public class ArrayBoundedStack<T> implements StackInterface<T> {
  4.  
  5.     private T[] elements;
  6.     private int topIndex;
  7.  
  8.     public ArrayBoundedStack(int bound) {
  9.         this.elements = (T[]) new Object[bound];
  10.         topIndex = -1;
  11.     }
  12.  
  13.     public void push(T element) {
  14.         topIndex++;
  15.         this.elements[topIndex] = element;
  16.     }
  17.  
  18.     public T popTop() {
  19.         T element = top();
  20.         pop();
  21.         return element;
  22.     }
  23.  
  24.     public void popSome(int i) {
  25.         for (int c = 0; c < i; c++) {
  26.             pop();
  27.         }
  28.     }
  29.  
  30.     public void pop() {
  31.         if (isEmpty()) {
  32.             throw new StackUnderflowException("Pop attempted on empty stack");
  33.         } else {
  34.             this.elements[topIndex] = null;
  35.             topIndex--;
  36.         }
  37.     }
  38.  
  39.     public T top() {
  40.         T topOfStack = null;
  41.         if (isEmpty()) {
  42.             throw new StackUnderflowException("Top attempted on empty stack");
  43.         } else {
  44.             topOfStack = this.elements[topIndex];
  45.         }
  46.         return topOfStack;
  47.     }
  48.  
  49.     public boolean swapStart() {
  50.         if (topIndex <= 0) {
  51.             return false;
  52.         } else {
  53.             T firstElement = this.elements[topIndex];
  54.             T secondElement = this.elements[ topIndex-1 ];
  55.             popSome(2);
  56.             push(firstElement);
  57.             push(secondElement);
  58.             return true;
  59.         }
  60.     }
  61.  
  62.     public boolean isEmpty() {
  63.         if (topIndex == -1) {
  64.             return true;
  65.         } else {
  66.             return false;
  67.         }
  68.     };
  69.  
  70.     public boolean isFull() {
  71.         if (topIndex == this.elements.length-1 ) {
  72.             return true;
  73.         } else {
  74.             return false;
  75.         }
  76.     }
  77.  
  78.     public int size() {
  79.         return this.topIndex+1;
  80.     }
  81.  
  82.     public String toString() {
  83.         String elements = "";
  84.  
  85.         for (int i = this.elements.length-1; i >= 0; i--) {
  86.             elements += "\n" + (i+1) + ") " + this.elements[i];
  87.         }
  88.  
  89.         return elements;
  90.     }
  91. }
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