Professional Documents
Culture Documents
Data Structures Via C++: Queue
Data Structures Via C++: Queue
Chapter 8:
Queue
Dr. Shaker El-Sappagh
Faculty of Computer Science and Engineering,
Galala University
Shaker.elsappagh@gu.edu.eg
What is a queue?
- Is a special kind of list.
- All of its items are added from one end (tail) and
removed from the other end (head).
- Queue preserve the order of items (FIFO data
structure).
- It is used in operating systems and networks
software (queuing theory).
Queue ADT
Characteristics:
- A queue store items (queueElementType) in FIFO.
Operations
- queueElementType dequeue ().
- void enqueue (queueElementType).
- queueElementType front ().
- bool isEmpty ().
Queue implementation using array
- Queue has double ends (front and rear).
- For array of size 4, some enqueue and dequeue are as follows:
enqueue(‘a’) a ? ? ? dequeue() a b c ?
f r f r
enqueue(‘b’) a b ? ? enqueue(‘d’) a b c d
f r f r
enqueue(‘c’) a b c ? dequeue() a b c d
f r f r
enqueue(‘e’) ???
- The array has empty places however, r can not move to the right.
Queue implementation using array (cont.)
- One solution is the circular queue. The end wraps to the front like
a circle.
- We still use array but we need r a
d
r and f to work in a circular way.
- We need maxQueue – 1 to point to f
the last element in the array, and C b
each add by 1 check if r or f equals
maxQueue – 1 .
- This operation will be done in a separate function e.g., nextPos.
Queue implementation using array (cont.)
- The question is: How to start the value of f and r. f
- When the queue has one element
then f == r, so r must start one step before f. r
- The check for empty queue is nextPos(r) == f.
f
- What is the problem with this implementation? r a
➢ The check for empty and full queue are the same.
- What is the solution to this problem?
➢ One way is to set f == r for empty queue, and f b
do not use the cell of f (real queue data is at a
nextPos(f) ).
d c
r
Queue implementation using array (cont.)
- What is the solution to this problem? f
r
➢ One way is to set f == r for empty queue, and
do not use the cell of f (real queue data is at
nextPos(f) ). r
f a
➢ The queue is full when nextPos(r) == f.
One cell of the array is wasted. Not avoidable.
f b
d c
r
Code Regular
const int maxQueue = 200;
template < class queueElementType > bool Queue < queueElementType >
::isEmpty()
{
return bool(f == 0);
}
Thanks