Return to the lecture notes index

Lecture 13 (October 4, 2006)

Queues

Consider queues in the real world. They can be found everywhere. We wait in a queue at the checkout in a supermarket. We wait in a queue to buy o tickets for a movie. When we arrive somewhere and a queue exists, we have to join the queue at the end (it is considered impolite to "cut" in front of people who are already in the queue). As people are processed, we move closer to the front of the queue, and we wait in the queue until we have moved all the way to the front, and then we are processed. We enter the queue at one end, and exit the queue on the other end.

Real-world queues can be easily modeled as a data structure. A queue is a first-in-first-out structure where we process the items in the same order in which we added them. The operations on a queue are:

Why Use Queues?

Queues don't have many operations defined upon them. It may seem like they are significantly less powerful than a vector or a linked-list. We can add to either end of a vector or a linked-list, and we can perform many other tasks with them as well. So why would we want to use a queue?

We use queues for the same reasons that we use them in the real world. Sometimes, fewer operations impose more of an order, and therefore make things run more efficiently. Imagine the checkout at a grocery store if there was more than the basic queue operations. Suppose cashiers could choose at random which customer they will process next, or suppose that customers could jump into the line at any random spot they choose. The result would be chaos and the efficiency would be lost.

This need for order is sometimes necessary in the computer world as well. When you print something in a cluster, the print job enters a queue, so the amount of time you have to wait for your printout is only dependent on the jobs that are in the queue in front of you. Suppose that you are trying to meet a deadline, and every now and then some other print job enters the queue ahead of you -- there would be no way to know how long it will take before your print request is processed.

Implementing Queues With Linked Lists

Now that we know what queues are, how do we go about building them? Well, we have already mentioned that vectors and linked-lists have all of the capabilities of queues, so it seems natural to build on top of them.

Building a queue using a linked list is quite trivial. enqueue() is implemented by adding to the tail of the list and dequeue() is implemented by removing from the head of the list. It is especially important to add to the tail and delete from the head, as opposed to adding to the head and deleting from the tail, on singly linked lists. To understand this, think carefully about the expense of deleting from the tail. With, or without, a tail reference -- it involves walking through the list to find the node prior to the tail. Deleting from the head is, however, quite inexpensive, since the head reference is always the predecessor of the head node. And, of course, adding to the tail of a sinly linked list, especially with a tail reference, is quite inexpensive -- only the tail node and the tail reference, itself, need to be updated in the common case.

Implementing Queues With ArrayLists

Let's see how they would be built using a vector. To model a queue with a vector, we need to add at one end of the vector and remove from the other. Since both adding and removing at index 0 are expensive operations in a vector, this model will be inefficent, regardless of which side of the vector we choose to be the front of the queue and which side we choose to be the end.

Suppose we impose one more restriction on our queue. Suppose that we limit the number of items that can be in the queue at any one time. If we do this, we can use the vector as a circular buffer.

To implement the fixed-size queue in a vector, we still need to implement the "enqueue" and "dequeue" operations. To do this, we define a "head" and "tail" index. When we insert an item into the queue, we increment the tail index and then insert it at tail index. When we remove an item from the queue, we remove it from the head index, and then increment the head index. If the head or tail index becomes higher than the number of items in the vector, we reset it to 0.

In order to make this work, all we have to do is make sure that the tail index never steps on the head index, because that would mean that we have overwritten one of the values in the queue. Otherwise, we can enqueue and dequeue as we please, and the head and tail indexes will circle through the vector and maintain the first-in-first-out behavior.

Let's take a look at how we could do this.

Implementing A Queue With A ArrayList
Implementing a queue with a vector requires us to impose a maximum number of elements that the queue can hold, and then using the vector as a circular buffer. Why do we need to do this? A queue requires us to add new items at one end and remove items from the other end, but either adding at or removing from the beginning of the vector causes all of the other elements in the vector to shift up or down. This is too time consuming, so we instead create a fixed-size vector and keep track of our current head and tail indexes. When we get to the end of the vector, we reset to 0 and keep going. In effect, this makes the linear ArrayList into a circular one -- 0 comes after the last element.

The following class implements a queue using a ArrayList.


import java.util.*;


/* This class implements a queue using a ArrayList.  It has the standard queue
 * operations enEqueue and deQueue, as well as a peek method to see the first
 * item without removing it, and an isEmpty method to check if there is
 * anything currently in the queue.
 *
 * Since we are implementing a queue, we have to fix the size of the ArrayList
 * that we are using.  This size is determined as a parameter to the
 * constructor.  The head and tail of the queue are managed by the headIndex
 * and tailIndex instance variables
 */
class ArrayListQueue
{
   private ArrayList queue;   // stores the items in the queue
   private int headIndex;  // the index of the first item to remove
   private int tailIndex;  // the index where we can add the next item


   /*
    * The constructor for the ArrayListQueue class.  It takes in the
    * number of items that the queue can hold as a parameter
    */
   public ArrayListQueue(int size)
   {
      // initialize the vector and set it to the specified size
      queue = new ArrayList(size);
      queue.ensureCapacity(size);
      for (int index=0; index< size; index++)
        queue.add(null);

      // start both the head and tail at the first spot in the vector
      headIndex = 0;
      tailIndex = 0;
   }


   /*
    * This method adds a new item to the queue at the tail
    */
   public void enQueue(Object addObj)
   {
      /*
       * check that the queue is not full.
       *
       * if the head and tail are the same, then either the queue is
       * empty or the queue is full.  if the queue is full, then the
       * index where the tail is will already have something in it
       */
      if ((headIndex == tailIndex) && (null != queue.elementAt(tailIndex)))
      {
         // throwing an Exception would probably be better, but we'll
         // keep it simple

         return;
      }


      /*
       * change the element at the tail index in the vector to reference
       * the new item.
       *
       * we have to use setElementAt() and not one of the add() or insert()
       * methods because we don't want to change the size of the vector
       */
      queue.setElementAt(addObj, tailIndex);

      // increment the tail index, or reset it to 0 if we reach the end
      tailIndex = (tailIndex + 1) % queue.size();
   }


   /*
    * This method removes the item at the head of the queue
    */
   public Object deQueue()
   {
      // create a new reference to the item we want to dequeue
      Object dequeueObj = queue.elementAt(headIndex);

      // if the reference is null, then the queue was empty
      if (dequeueObj == null)
      {
         return null;
      }

      /*
       * remove the item from the vector by setting the head index to null
       *
       * we have to use setElementAt() because removeElementAt() shifts
       * the items after the head, which we don't want
       */
      queue.setElementAt(null, headIndex);

      // increment the head index, or reset it to 0 if we reach the end
      headIndex = (headIndex + 1) % queue.size();

      // return the object that we remove from the queue
      return dequeueObj;
   }


   /*
    * This method returns the object at the head of the queue, but does
    * not remove it
    */
   public Object peek()
   {
      // return the object that is currently at the head index
      return queue.elementAt(headIndex);
   }


   /*
    * This method tests whether or not the queue is currently empty
    *
    * if there is nothing at the head index, then there is nothing in
    * the queue
    */
   public boolean isEmpty()
   {
      // return true if the queue is empty, false otherwise
      return (null == queue.elementAt(headIndex));
   }
}