/* * Stack.java * * Created on March 17, 2008, 10:17 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package parenmatchapplet2; /** * * @author suchenek */ public class Stack { private int count; private int capacity; private int capacityIncrement; private Object[] itemArray; /** Creates a new instance of Stack */ public Stack() { count=0; capacity=10; capacityIncrement=2; itemArray=new Object[capacity]; } public void push(Object newItem) { if(count==capacity) //no more space, "resize" the array up { capacity*=capacityIncrement; Object[] tempArray = new Object[capacity]; System.out.println("New stack of capacity " + capacity); for (int i = 0; i < count; i++) { tempArray[i] = itemArray[i]; cnt.incr(); // cnt.outln(" push resize incr "); } itemArray = tempArray; } cnt.incr(); //insert at the end itemArray[count++] = newItem; } public Object pop() { Object itemToReturn; if (count==0) return null; cnt.incr(); itemToReturn=itemArray[--count]; if ((count < capacity / capacityIncrement) && (10 <= capacity / capacityIncrement)) //space wasted, "resize" the array down { capacity/=capacityIncrement; Object[] tempArray = new Object[capacity]; System.out.println("New stack of capacity " + capacity); for (int i = 0; i < count; i++) { tempArray[i] = itemArray[i]; cnt.incr(); // cnt.outln(" pop resize incr "); } itemArray = tempArray; } return itemToReturn; } public int size() { return count; } public boolean isEmpty() { return count==0; } public int Length() { return itemArray.length; } }