// file: MyPriorityQueue.java // author: Robert Keller // purpose: Implement PriorityQueue interface /** * A Priority is a repository for Comparables. * Objects are inserted using enqueue and removed using dequeueMin, * which always returns the minimum in the Comparable ordering. * This implementation maintains the items in increasing order at all times. */ class MyPriorityQueue implements PriorityQueue { /** * reference to the first PCell in the queue, which is always the minimum * Comparable in the PriorityQueue. */ protected PCell head; /** * Construct a MyPriorityQueue. */ MyPriorityQueue() { head = null; } /** * Insert an Comparable in the PriorityQueue. * * @param item the Comparable to be inserted */ public void enqueue(Comparable item) { // If the PriorityQueue is empty, or the item to be inserted is the // new minimum, it goes at the head of the queue. if( head == null || item.compareTo(head.data) < 0 ) { head = new PCell(item, head); return; } // If the PriorityQueue is non empty and the item to be inserted is // not the new minimum, then find the PCell that will come before it // and insert it in the list. for( PCell ptr = head; ptr != null; ptr = ptr.next ) { if( ptr.next == null || item.compareTo(ptr.next.data) < 0 ) { ptr.next = new PCell(item, ptr.next); return; } } } /** * Remove the minimum Comparable from the PriorityQueue. * * @return the Comparable removed * @exception EmptyQueueException if the PriorityQueue is empty */ public Comparable dequeueMin() throws EmptyQueueException { if( head == null ) { throw new EmptyQueueException(); } Comparable result = head.data; head = head.next; return result; } /** * Indicate whether or not the PriorityQueue is empty * * @return boolean indicating whether or not the Queue is empty */ public boolean isEmpty() { return head == null; } /** * Cell containing a PriorityQueue element */ class PCell { /** * the data item */ Comparable data; /** * reference to the PCell containing the next greater data item */ PCell next; /** * construct a PCell * @param _data the data item in the PCell * @param _next reference to a PCell containing the next larger data item */ PCell(Comparable _data, PCell _next) { data = _data; next = _next; } } }