// CSE 373, Winter 2013, Marty Stepp // This class defines an implementation of the stack ADT using an array // as the internal data structure. import java.util.Arrays; import java.util.EmptyStackException; import java.util.Iterator; import java.util.NoSuchElementException; public class ArrayStack implements Stack { private E[] elements; private int size; // Constructs a new empty stack. @SuppressWarnings("unchecked") public ArrayStack() { elements = (E[]) (new Object[5]); size = 0; } // Returns true if the stack does not contain any elements. public boolean isEmpty() { return size == 0; } // Returns an Iterator to traverse the elements of this stack. public Iterator iterator() { return new ArrayStackIterator(); } // Returns the top element of this stack without removing it. // Throws an EmptyStackException if the stack is empty. public E peek() { if (size == 0) { throw new EmptyStackException(); } return elements[size - 1]; } // Removes and returns the top element of this stack. // Throws an EmptyStackException if the stack is empty. public E pop() { if (size == 0) { throw new EmptyStackException(); } E top = elements[size - 1]; elements[size - 1] = null; size--; return top; } // Adds the given value to the top of this stack. public void push(E value) { if (size == elements.length) { resize(); } elements[size] = value; size++; } // Returns the number of elements contained in this stack. public int size() { return size; } // Returns a string representation of the stack, such as "bottom a b c top". public String toString() { StringBuilder sb = new StringBuilder(); sb.append("bottom "); for (int i = 0; i < size; i++) { sb.append(elements[i]); sb.append(' '); } sb.append("top"); return sb.toString(); } // copies the stack's data into an array twice as large @SuppressWarnings("unchecked") private void resize() { E[] newElements = (E[]) (new Object[2 * size]); for (int i = 0; i < size; i++) { newElements[i] = elements[i]; } elements = newElements; } // An iterator class to traverse the elements of this stack // from top to bottom. private class ArrayStackIterator implements Iterator { private int index; // Constructs an iterator at the beginning (bottom) of this stack. public ArrayStackIterator() { index = size - 1; } // Returns true if there are any more elements for this iterator to return. public boolean hasNext() { return index >= 0; } // Returns the next element from the stack and advances iterator by one slot. public E next() { if (!hasNext()) { throw new NoSuchElementException(); } E result = elements[index]; index--; return result; } // Not implemented. public void remove() { throw new UnsupportedOperationException(); } } }