/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mystack; /** * * @author kvaradar */ public class MyStack implements Stack { // homepage.cs.uiowa.edu/~kvaradar/fall2013/ds.html Object [] myArray; int top; public static final int CAPACITY = 1000; public MyStack() { myArray = new Object[CAPACITY]; top = -1; } public int size() { // O(1) return (top + 1); } public boolean isEmpty() { // O(1) return (size() == 0); } public void push(Object a) { // Let n be size. // normal push: O(1) // resizing push: O(n) if (size() == myArray.length) { Object [] tempArray = new Object [2 * myArray.length]; for (int i = 0; i < myArray.length; i++) tempArray[i] = myArray[i]; myArray = tempArray; } myArray[top + 1] = a; top = top + 1; } public Object top() { // O(1) //exceptional case: method called when stack empty return myArray[top]; } public Object pop() { // O(1) //exceptional case Object temp = myArray[top]; top--; myArray[ top + 1] = null; //facilitate garbage collection return temp; } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } public static void reverse(Object [] arr, Stack sta) { for (int i = 0; i < arr.length; i++) sta.push(arr[i]); for (int i = 0; i < arr.length; i++) arr[i] = sta.pop(); } }