//DropoutStack class for CMPSCI187 Project 3 public class DropoutStack { public static final int DEFAULT_CAPACITY = 3; private T[] myStack; private int top; private int bottom; private int capacity; private int size; //default constructor takes no parameters, uses default capacity public DropoutStack() { this(DEFAULT_CAPACITY); } //creates a new stack of the given capacity public DropoutStack(int c) { myStack = (T[]) (new Object[c]); top = -1; bottom = 0; capacity = c; size = 0; } //pushes the element onto the top of the stack public void push (T element){ top = (top + 1) % capacity; myStack[top] = element; if (isFull()) bottom = (bottom + 1) % capacity; else size++; } //removes and returns the top element of the stack public T pop() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("You are trying to peek at an empty stack."); T topElement = (T) myStack[top]; if (top == 0) top = capacity - 1; else top--; size--; return topElement; } //returns the top element of the stack without removing it public T peek() throws EmptyCollectionException{ if (isEmpty()) throw new EmptyCollectionException("You are trying to peek at an empty stack."); return (T) myStack[top]; } //return true if stack has no elements, false otherwise public boolean isEmpty(){ return (size() == 0); } //helper method to check is the stack is at capacity public boolean isFull(){ return (size() == capacity); } //determine the size of the stack public int size(){ return size; } //resize the stack if more space is needed public void resize(int newCapacity){ /* A student in office hour told me you had asked that * top resets to 0 when the stack is doubled. Below is * the implementation according to that specification, * but it results in incorrect behavior because when * new elements are pushed after resizing, indices wraps * around and popping results in popping null elements * *T[] newStack = (T[]) (new Object[newCapacity]); int index = 0; for (int k = top; k < newCapacity + top; k++){ if (k < capacity) //copy all the old elements there is room for newStack[index] = myStack[k]; else //pad new stack with null elements if larger newStack[index] = null; index++; } myStack = newStack; bottom = size - top; top = 0; capacity = newCapacity; }*/ T[] newStack = (T[]) (new Object[newCapacity]); int index = 0; for (int k = 0; k < newCapacity; k++){ if (k < capacity) //copy all the old elements there is room for newStack[k] = myStack[k]; else //pad new stack with null elements if larger newStack[k] = null; } myStack = newStack; bottom = size - top; capacity = newCapacity; } }