package queues; import list.*; import list.visitor.*; import java.util.Enumeration; /** * A queue implemented using ALists. * * Version 1. * * @author Alan L. Cox * @since 03/15/01 */ public class AListQueue implements IQueue { //Uses two lists, the contents are the first list contents //followed by the sencond list's reversed contents. private AList _objects1 = ListFactory.Singleton.makeEmptyList(); private AList _objects2 = ListFactory.Singleton.makeEmptyList(); /** * Adds an object to the AListQueue by adding it to the second list. * @param object the object to enqueue * This enqueue method takes O(1) time since it only adds to the front of * the lis */ public void enqueue(Object object) { _objects2 = ListFactory.Singleton.makeNEList(object, _objects2); } /** * Removes the first object from the AListQueue. * @return the dequeued object * This dequeue method takes O(1) */ public Object dequeue() { if(((Boolean)_objects1.execute(IsEmpty.Singleton, null)).booleanValue()) if(((Boolean)_objects2.execute(IsEmpty.Singleton, null)).booleanValue()) throw new java.util.NoSuchElementException("The queue is empty."); if(((Boolean)_objects1.execute(IsEmpty.Singleton, null)).booleanValue()) { _objects1 = (AList)_objects2.execute(Reverse.Singleton, null); _objects2 = ListFactory.Singleton.makeEmptyList(); } Object object = _objects1.getFirst(); _objects1 = _objects1.getRest(); return object; } /** * Enumerates the queue from oldest to newest element. * @return an Enumeration of the queue. * This enumeration takes O(1) time since it only contains single statements. */ 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 list1, AList list2) { _next = (AList)list1.execute(Append.Singleton, list2.execute(Reverse.Singleton, null)); } 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(_objects1, _objects2); } }