LEC - 3 Queue
LEC - 3 Queue
dequeue
enqueue (remove from
(add at rear) Front(
The Queue Operations
A queue is like a line of people waiting for a bank teller. The queue has a front and a
rear.
Queue underflow
The condition resulting from trying to remove an element from an
empty queue.
if(!q.IsEmpty())
q.Dequeue(item);
Queue Array Implementation
A queue can be implemented with an array, as shown
here. For example, this queue contains the integers
4 (at the front), and 6 (at the rear).
Rear
Front enqueue
[0] [1] [2] [3] [4] [5] ...
dequeue
4 8 6
An array of integers
to implement a We don't care what's in
queue of integers this part of the array.
When an element leaves ➢ When an element enters
the queue, size is the queue, size is incremented,
decremented, and front and rear changes, too.
changes, too.
At the End of the Array
There is special behaviour at the end of the array. For example,
suppose we want to add a new element to this queue, where the
rear index is [5]:
Problem:
when rear reaches the end of the array, we can't enqueue
anything else
Ex: Suppose that:
The array size is 16
We have performed 16 pushes
We have performed 5 pops
The queue size is now 11
We perform one further push
In this case, the array is not full and yet we cannot
place any more objects in to the array
Idea :Circular Queue
▪ When rear reaches the end of the array ,put the next element
at index 0 .Next after that goes at index 1
▪ front wraps around in the same way
▪ Use all the extra space that's left in the beginning of the array
after we dequeue!
Circular Queue
Instead of viewing the array on the range 0, …, 15,
consider the indices being cyclic:
…, 15, 0, 1, …, 15, 0, 1, …, 15, 0, 1, …
This is referred to as a circular array
• Queues are widely used as waiting lists for a single shared resource like a
printer.
For example, in downloading from web server, those requests not
currently being downloaded are marked as “Queued”