Stacks vs. Queues

A Queue is a data abstraction similar to a Stack, but

whereas a Stack pops the most recent element entered, i.e. the youngest, a Queue removes the earliest element entered, i.e. the oldest.

A Queue is efficiently constructed by keeping a reference to the last cell of the list as well as the first.

For the moment, we will leave the construction of a Queue as an exercise.

The operations on a queue are typically called:

enqueue: add an element to the queue

dequeue: remove oldest element in the queue

The following diagrams show how a Queue would work:

A Queue with four elements

 

 

The Queue above after dequeue(); item a is returned.

 

The Queue above after enqueue(e).

 

The empty Queue

For the empty Queue, it is adequate to have only one of the references set to null; it depends on how emptiness is checked.

 

Linked lists are not the only way to construct Stacks and Queues; arrays may be used instead:

Source files containing array implementations of Stack and Queue:

Stack.java

Queue.java

These are worth examining, as they show how to reallocate arrays in case the stack or queue grows too large.

In the case of a queue, Queue.java shows how to reuse existing space in a queue in a circular fashion, so that reallocation is not done unless absolutely necessary.

Next Slide Previous Slide Contents