UMBC CS 201, Spring 99
 UMBC CMSC 201 Spring '99 CSEE | 201 | 201 S'99 | lectures | news | help

# The Queue

## Implementation using an array

It is quite possible to use an array to implement a queue, but we would suffer all the same space limitations that we have all along with arrays.

We would have to guess about how big the queue could possibly get, declare an array to be of that size, and then start enqueueing items. We would just have to hope that our guess was correct, so that the array could hold the entire queue. Otherwise we'd have to abort the program.

Since in our simple example, this array would be holding ints, we would have to initialize all of the elements of the array to hold some integer that wouldn't be a valid integer for this particular application, possibly 0 or -1.

In this implementation, the pointer head would hold the same address as the name of the array. If the queue is empty, the pointer tail would also hold the same address as the name of the array.

Enqueueing is not a big problem, we would just put a value into the first "empty" element of the array and move the pointer named tail, by using the statement tail = &(array[j]);, where j is the index of the element just filled.

Dequeueing is somewhat of a problem. Since when we dequeue something, it has to be removed from the beginning of the queue (remove array[0]), we will need to move all other values forward by one element in the array. As in:

i = 1; while (array[i] != 0) { array[i - 1] = array[i]; i++; } There dequeueing is quite time consuming.

If we think about implementing the queue using an array, not only are we wasting space, but we are also wasting time. Sometimes it's okay to waste space if it will save us time. Other times it's okay to waste time to save space. It all depends on the needs of the application and there is usually a tradeoff between space and time. It is never okay to waste both space and time. So even though it is possible to implement a queue using an array, it isn't usually done.

## Implementation using a linked list

Since we now know about linked lists, we should consider using a linked list implementation of the queue. The queue can be implemented without wasting any space, and by keeping pointers to both the beginning of the list (the head) and the end of the list (the tail), we can make our queue work much faster than an array implementation.