package stacks; import list.*; import list.visitor.*; import java.util.Enumeration; /** * A stack implemented using AList. * * A stack manages its objects in a Last In, First Out (LIFO) order. * * @author Alan L. Cox * @since 03/15/01 */ public class AListStack implements IStack { private AList _objects = ListFactory.Singleton.makeEmptyList(); /** * Adds a new object to the stack. * @param data the new object to add to the stack. * This push method takes O(1) since it only adds the element to the front */ public void push(Object data) { _objects = ListFactory.Singleton.makeNEList(data, _objects); } /** * Removes and returns the newest object from the stack. * * @return the popped object * This pop method takes O(1) time since it only removes the from element from the list. */ public Object pop() { if(((Boolean)_objects.execute(IsEmpty.Singleton, null)).booleanValue()) throw new java.util.NoSuchElementException("The stack is empty."); Object object = _objects.getFirst(); _objects = _objects.getRest(); return object; } /** * Enumerates the stack from newest to oldest. * @return an Enumeration of the stack. * hasMoreElements: O(1) since IsEmpty as implemented takes O(1) * nextElement: the most it does is chop off the first element from the list */ public Enumeration enumeration() { /** * We can't use an anonymous inner class to implement this * Enumeration because of the cosntructor. */ class AListEnumeration implements Enumeration { private AList _next; AListEnumeration(AList alist) { _next = alist; } public boolean hasMoreElements() { return !(((Boolean)_next.execute(IsEmpty.Singleton, null)).booleanValue()); } public Object nextElement() { return _next.execute(new IListAlgo() { public Object forEmpty(AList host, Object input) { return null; } public Object forNonEmpty(AList host, Object input) { Object object = _next.getFirst(); _next = _next.getRest(); return object; } }, null); } } return new AListEnumeration(_objects); } }