Queue 2
Queue 2
Queues
2
Introduction to Queues
What is a queue?
Queue operations.
Queue implementations.
Queue As Array
Queue As Circular Array
Applications of queue.
Array Implementation of Queue
3
n-1 3 2 1 0
DCBA
After A leaves,
n-1 3 2 1 0
DCB
n-1 3 2 1 0
Y X ……
rear front
5
Two Solutions
A
n-1 3 2 1 0 n-1 3 2 1 0
leaves
…… CBA …… CB
rear=
3
Wrapped around array 3
2
n-1 3 2 1 0 front= 1 BC
…… CBA 0
0 A
EnQueue • DeQueue
rear = (rear + 1) MOD n – front = (front + 1) MOD n
3 rear=3 front=1 3
2 2
1 BC 1 BC
0 A 0
n- n-
1 1
8
Empty/Full In Circular Array
When rear equals front, Queue is empty
When (rear + 1) MOD n equals front, Queue is
full
Circular array with capacity n at most can hold n-
1 items.
Implementation for CQueue
9
Interface
Users don’t need to know how Queue is implemented.
User only need to know how they can operate the
Queue.
There are many ways to implement Queue, but all of
them have the same interfaces
enqueue, dequeue, peek, isFull, isEmpty
Implementation for Circular Queue
10
queuest cq;
int nn;
CQueue.initialize(&cq);
for(;;)
{
// main1.h: interface for the main class.
cout<<endl;
#include "cqueue.h“
cout<<"*****************************"<<endl; …
cout<<"*1- Insertion operation *"<<endl; …
cout<<"*2- Delete operation *"<<endl; cqueue CQueue;
cout<<"*3- Display operation *"<<endl; ….
…..
cout<<"*4- Exit *"<<endl;
cout<<"****************************"<<endl;
cout<<" Enter your (1-4) :";cin>>nn;
cout<<endl;
switch (nn)
16 {
case 1:
cout<<endl<<"Enter the no. of element";
cin>>n1;
for(i=0;i<n1;i++)
{
cout<<"Enter the element...";
cin>>m;
CQueue.enqueue(&cq,m);
CQueue.printcq(&cq);
}
break;
case 2:
cout<<CQueue.dequeue(&cq)<<" ";
break;
case 3:
CQueue.printcq(&cq);
break; }
}
Applications of Queue
17
Homework:-
1-Program to implement insert and delete operations on Priority Queue .