- Forward


An Introduction to Queues
With Examples in C++


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Queues are very straightforward but are slightly more complicated than stacks
  • Queues can be implemented in a number of different ways using the same data structure (i.e., with different algorithms)
  • So, they are a good ADT to consider next
An Analogy: A Waiting Line
Back SMYC Forward
  • When you add a person to the line they go to the back
  • People are served from the front (first-in-first-out or FIFO)
A Definition of a Queue
Back SMYC Forward

    Queue
    Values: Homogeneous elements of any type.
    Operations:
    Name/Operator Arguments Returns
    Constructor A new instance.
    enqueue/append
    element The element to add to the rear of the queue
    dequeue/serve The element at the front of the queue
    isEmpty true if the queue is empty and false o/w

In addition, if the stack has a "size limit", one could add an isFull() operation; some people add a peek() operation; and some people add a makeEmpty() operation.

An Array Implementation with Constant Shuffling
Back SMYC Forward
  • Enqueue/append to the rear
  • Dequeue/serve from the front (index 0)
  • "Shuffle" after each serve
  • An Analogy: A normal waiting line
Constant Shuffling (cont.)
Back SMYC Forward
cppexamples/arrayqueue/shuffling/Queue.h
 
cppexamples/arrayqueue/shuffling/Queue.cpp
 
An Array Implementation with Periodic Moving
Back SMYC Forward
  • Keep a "pointer" to the front and rear elements
  • Move all of the elements down when space at the back runs out
  • One Analogy: A waiting line in which the server moves (until space runs out)
  • Another Analogy: A clock in which the ticks are on a line, not a circle
Periodic Moving (cont.)
Back SMYC Forward
cppexamples/arrayqueue/moving/Queue.h
 
cppexamples/arrayqueue/moving/Queue.cpp
 
A Circular Array Implementation
Back SMYC Forward
  • Keep a "pointer" to the front and rear elements
  • Have the "pointers" wrap around
  • An Analogy: A circular waiting line in which the server moves
Circular Implementation (cont.)
Back SMYC Forward
cppexamples/arrayqueue/circular/Queue.h
 
cppexamples/arrayqueue/circular/Queue.cpp
 
There's Always More to Learn
Back -