import java.util.Arrays; public class Stack { // length of the array private static int SIZE = 10; // the stack is an array private static int[] A = new int[SIZE]; // cursor to next available slot in array, initialized to empty stack private static int next = 0; // put a new int on top of the stack public static void push(int n) { if (next == SIZE) { // overflow! resize(); } A[next] = n; ++next; } // Copied from HW 02 private static void resize() { int[] T = new int[SIZE * 2]; for(int i = 0; i < A.length; ++i) { T[i] = A[i]; } SIZE = SIZE * 2; A = T; } // remove top int from the stack and return it public static int pop() { --next; int n = A[next]; A[next] = 0; // not necessary, but shows structure of stack return n; } // return top int without removing it public static int top() { return A[next-1]; } // number of ints in the stack public static int size() { return next; } // is the stack empty? public static boolean isEmpty() { return next == 0; } // just for debugging and tracing private static void printStack() { System.out.println("\nStack: " + Arrays.toString(A) + "\t next: " + next); } public static void main(String[] args) { System.out.println("\nUnit Test for Stack ADT"); // test size and isEmpty on empty stack System.out.println("\nsize() => " + size()); System.out.println("\nisEmpty() => " + isEmpty()); System.out.println("\nPush 3, 6 and 7: "); push(3); push(6); push(7); printStack(); System.out.println("\nsize() => " + size()); System.out.println("\nisEmpty() => " + isEmpty()); System.out.println("\npop() => " + pop()); System.out.println("\npop() => " + pop()); System.out.println("\nPush 7:"); push(7); printStack(); System.out.println("\nsize() => " + size()); System.out.println("\nisEmpty() => " + isEmpty()); // Now test resizing for(int i = 9; i<100; i += 2) { push(i); } printStack(); while(!isEmpty()) { pop(); } printStack(); System.out.println("\nsize() => " + size()); System.out.println("\nisEmpty() => " + isEmpty()); } }