SHARE
TWEET

Untitled

a guest Oct 18th, 2019 85 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ph.edu.dlsu.datsral;
  2.  
  3. import java.util.NoSuchElementException;
  4.  
  5. public class MyStack<T> {
  6.  
  7.     private static final int INITIAL_CAPACITY = 4;
  8.     private GenericArray<T> data;
  9.     private int capacity;
  10.     private int count;
  11.  
  12.     public MyStack() {
  13.         capacity = INITIAL_CAPACITY;
  14.         data = new GenericArray<T>(capacity);
  15.         count = 0;
  16.     }
  17.  
  18.     public T top() {
  19.         if (empty()) throw new NoSuchElementException("Stack is Empty (Underflow)");
  20.         return data.get(count - 1);
  21.     }
  22.  
  23.     public void push(T value) {
  24.         if (count == capacity) {
  25.             ensureCapacity();
  26.         }
  27.         data.set(count++, value);
  28.     }
  29.  
  30.     T pop(){
  31.         if (empty()) throw new NoSuchElementException("Stack is Empty (Underflow)");
  32.         return data.get(--count);
  33.     }
  34.  
  35.     private void ensureCapacity() {
  36.         System.out.println("Resizing...");
  37.         capacity *= 2;
  38.         GenericArray<T> newArray = new GenericArray<T>(capacity);
  39.         for (int i = 0; i < count; i++) {
  40.             newArray.set(i, data.get(i));
  41.         }
  42.         data = newArray;
  43.     }
  44.  
  45.     public int size() {
  46.         return count;
  47.     }
  48.  
  49.     public boolean empty() {
  50.         return count == 0;
  51.     }
  52.  
  53.     class GenericArray<T> {
  54.  
  55.         private Object[] data;
  56.  
  57.         public GenericArray(int n) {
  58.             data = new Object[n];
  59.         }
  60.  
  61.         public int size() {
  62.             return data.length;
  63.         }
  64.  
  65.         public T get(int idx) {
  66.             return (T) data[idx];
  67.         }
  68.  
  69.         public void set(int idx, T item) {
  70.             data[idx] = item;
  71.         }
  72.     }
  73. }
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
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top