package rebelsky.linear; /** * A linked implementation of priority queues. */ public class LinkedPQ implements PriorityQueue { // +-------+-------------------------------------------------------- // | Notes | // +-------+ /* We use a set of QueueNodes to implement linked queues. We store the values in order, from smallest to largest. We determine the priority of the object by using a Comparator which is supplied as part of the constructor. */ public class LinkedQueue implements Queue { // +--------+------------------------------------------------------- // | Fields | // +--------+ /** How to order the objects. */ Comparator c; /** The node at the front of the queue. */ QueueNode front; // +-------------+-------------------------------------------------- // | Construtors | // +-------------+ /** * Build a new queue. */ public LinkedQueue(Comparator _c) { this.c = _c; this.front = null; } // LinkedQueue() // +---------+------------------------------------------------------ // | Methods | // +---------+ /** * Add an element to the end of the queue. * * @param val * The object that is to be added. * @post * The queue now contains an additional copy of val. */ public void put(Object val) { // Create a new node for the end of the queue. QueueNode newback = new QueueNode(val); // Put this new node after the current back this.back.next = newback; // Update our knowledge of the back of the queue this.back = newback; } // put(Object) /** * Remove the least-recently-added element that is still in the * queue. * * @return val * An object in the queue. * @pre * The queue is not empty. * @post * The queue contains one fewer copy of val. * @post * Every value in the queue was added more recently than val. */ public Object get() { // Extract the value from the front. Object val = this.front.contents; // Eliminate the front node by advancing to the next node. this.front = this.front.next; // Return the extracted value. return val; } // get() /** * Determine which object will next be returned by get. * * @return val * An object in the queue. * @pre * The queue is not empty. * @post * Every value in the queue was added less recently than val. */ public Object peek() { // The value to be returned is the contents for the front. return this.front.contents; } // peek() /** * Determine if the queue is empty. */ public boolean isEmpty() { // The queue is empty if and only if front is null. return front == null; } // isEmpty() } // class LinkedQueue } // class LinkedPQ