import java.util.EmptyStackException; /** * A simple linked list based integer stack. * * @author John Kloss */ public class IntStackTwo { /** * Simple node class used as the linked list components for the * stack. */ class Node { int value; // value this node contains Node next; // node below this one in the stack /** * Creates a new Node with integer value, value and * a pointer to Node, next. * * @param value The integer value this Node should contain. * @param next The Node which lies (abstractly) below this * Node in the stack. */ Node(int value, Node next) { this.value = value; this.next = next; } } Node stackPtr = null; // pointer to the top of the stack /** * Creates an empty integer stack. */ public IntStackTwo() { // do nothing } /** * Returns whether this stack is empty. * * @return true if this stack is empty; false * otherwise. */ public boolean isEmpty() { return (stackPtr == null); } /** * Pushes an integer onto the top of this stack. * * @param value The integer to push onto this stack. */ public void push(int value) { stackPtr = new Node(value, stackPtr); } /** * Pops an integer from the top of this stack. * * @return The last integer pushed onto this stack. * * @exception EmptyStackException * Thrown if this stack contains no integers. */ public int pop() { //////////////////////////////////////// // Note: EmptyStackException is defined // in java.util. if (stackPtr == null) throw new EmptyStackException(); else { int retValue = stackPtr.value; stackPtr = stackPtr.next; return retValue; } } //////////////////////////////////////// // Test our stack implementation public static void main(String[] args) { IntStackTwo s = new IntStackTwo(); for (int i = 0; i < 20; i++) { System.out.println("Pushing: " + i); s.push(i); } while (s.isEmpty() == false) System.out.println("Popping: " + s.pop()); } }