import java.util.*; public class StackExample { public static void main (String[] argv) { // This example uses String's. originalExample (); // This one uses numbers. exampleWithIntegers (); // We'll implement our own stack. stackInternalsExample (); } static void originalExample () { // The Java library has a Stack data structure. Here, we'll // make a stack to hold strings. Stack toDoList = new Stack (); // Add some strings. toDoList.push ("Pay bills"); toDoList.push ("Clean room"); toDoList.push ("Do homework"); toDoList.push ("See movie"); toDoList.push ("Hang out"); // Print. System.out.println ("Priorities: "); while (! toDoList.isEmpty() ) { String nextPriority = toDoList.pop (); System.out.println (" " + nextPriority); } } static void exampleWithIntegers () { // Now use Integer instead of String. // Note: we don't declare it as Stack but Stack, // because Integer's are objects while int's are not. Yet, // Java allows using these structures with int's (through // a feature called autoboxing). Stack intStack = new Stack (); // Add some values. intStack.push (1); intStack.push (2); intStack.push (3); // Print. System.out.println ("Extracting from intStack: "); while (! intStack.isEmpty() ) { System.out.println ( " " + intStack.pop() ); } } // We'll use a simple array as the underlying structure. // This stack is for real numbers (double's). static double[] myStack; // This will tell us where in the array the top-element is: static int stackTop; // A method to get the array set up. static void initializeStack () { myStack = new double [100]; stackTop = -1; } // push() takes a double. static void push (double value) { stackTop ++; myStack[stackTop] = value; } // pop() returns a double. static double pop () { double value = myStack[stackTop]; stackTop --; return value; } // See if it's empty. static boolean isEmpty () { if (stackTop < 0) { return true; } else { return false; } } static void stackInternalsExample () { // Similar to stack creation. initializeStack (); // Put stuff in. push (3.141); push (2.718); push (1.618); // Like before, extract using pop() while (! isEmpty() ) { double value = pop (); System.out.println ("Removed: " + value); } } }