package closedlist; import openlist.OpenList; /** * A OLStack constructed using an OpenList * @author Robert Keller */ public class OLStack { /** * contents contains the objects in the stack, for newest to oldest. */ OpenList contents; /** * Construct an empty stack. */ public OLStack() { clear(); } /** * Push the newest value onto the stack * @param value */ public void push(Object value) { contents = OpenList.cons(value, contents); } /** * Remove the newest value from the stack and return it. * @return the newest value that was on the stack. */ public Object pop() { Object result = contents.first(); contents = contents.rest(); return result; } /** * Return true if the stack is empty, false otherwise. * @return */ public boolean isEmpty() { return contents.isEmpty(); } /** * Return true if the stack is non-empty, false otherwise. * @return */ public boolean nonEmpty() { return contents.nonEmpty(); } /** * Clear all elements from the stack */ public final void clear() { contents = OpenList.nil; } /** * Test a stack crudely, by pushing on integers, then * popping and checking that the popped values agree with what is * expected. */ public static void main(String arg[]) { OLStack stack = new OLStack(); int i; for( i = 0; i < 100; i++ ) { stack.push(i); } while( stack.nonEmpty() ) { int actual = (Integer)stack.pop(); if( --i != actual ) { System.out.println("Stack failed at " + i); } } } }