package stackImplementation; public class Stack { // The maximum possible size of a stack. public static final int MaxSize = 100; // The array index of the last active element // in the stack. A value of -1 means the stack // is currently empty. private int top = -1; // The stack elements, stored in an array. private Object[] store = new Object[MaxSize]; // Number of all pushes (collectively) // done to all stacks. private static int totalNumberOfPushes = 0; // Add a new element at the top of the stack // (if there’s space left). public void push(Object newItem) { if (top < MaxSize - 1) { top++; store[top] = newItem; totalNumberOfPushes++; } else { System.out.println("Sorry, stack full."); } } // Remove the top element of the stack and return // it; check that the stack has elements in it! public Object pop() { Object ans = ""; if (top >= 0) { ans = store[top]; top--; } else { System.out.println("Sorry, stack empty."); } return ans; } // Return the number of elements that are // currently in the stack. public int size() { return top + 1; } // Return the total number of pushes // done to all stacks (collectively). public static int getNumberOfPushes() { return totalNumberOfPushes; } // Print the stack from top to bottom. // (not a standard function of stacks!) public void print() { int i; for (i = top; i >= 0; i--) { System.out.println(store[i]); } } // ============================================================= // Below are the 2 new methods that the students need to define: // ============================================================= // Return the top element of the stack without removing // it; check that the stack has elements in it! public Object peek() { Object ans = ""; if (top >= 0) { ans = store[top]; } else { System.out.println("Sorry, stack empty."); } return ans; } // Check if the stack has no elements in it -- return // true if the stack is empty, otherwise return false. public boolean isEmpty() { if (top >= 0) { return false; } else { return true; } } }