/** realizza l'interfaccia Stack usando un array come struttura dati */ public class MyStack implements Stack { private Object[] a; private int size; public MyStack() { a = new Object[1]; makeEmpty(); } /** O(1) nel caso migliore (senza ridimensionamento dell'array), O(n) nel caso peggiore (con ridimensionamento dell'array) */ public void push(Object obj) { if (size >= a.length) { Object[] newA = new Object[2 * a.length]; for (int i = 0; i < a.length; i++) newA[i] = a[i]; a = newA; } a[size] = obj; size++; } /** O(1) */ public Object pop() throws EmptyStackException { if (isEmpty()) throw new EmptyStackException(); Object tmp = a[size - 1]; a[size - 1] = null; size--; return tmp; } /** O(1) */ public Object top() throws EmptyStackException { if (isEmpty()) throw new EmptyStackException(); return a[size - 1]; } public int size() { return size; } public boolean isEmpty() { return size == 0; } public void makeEmpty() { size = 0; } }