Data Structure Module-3 Queue
Data Structure Module-3 Queue
Algorithms
Module -3
Queue
Dr. R. Jothi, SCOPE
VIT Chennai
Outline
Queue data structure
Array Implementation
Applications
5 0
5 3 12 4
0 1 2 3 4 5 6 7 8 9
-1 0 1 2 3 4 5 6 7 8 9
int IsEmpty(Q)
Empty Queue {
-1 0 1 2 3 4 5 6 7 8 9
int IsEmpty(Q)
{
Empty Queue
if (front == -1 && rear==-1)
front -1
return 1;
rear -1
return 0;
} Dr. R. Jothi, VIT Chennai
Enqueue : insert x into Q
front rear
Enqueue
9 2 5
rear rear +1
Before
0 1 2 3 4 5 6 7 8 9 Q[rear] x
front rear
• Suppose if Q is empty?
• Inserting first entry
After 9 2 5 x
• Suppose if Q is full ?
0 1 2 3 4 5 6 7 8 9
Q[rear]= x;
} Dr. R. Jothi, VIT Chennai
How do you check whether Queue is Full?
front rear
rear = Maxsize-1
9 2 5 11 7 23 4 1 6 3
0 1 2 3 4 5 6 7 8 9
front rear
Is this Q full?
Free slots at front can not be
reused 5 11 7 23 4 1 6 3
Solution
0 1 2 3 4 5 6 7 8 9
Circular Queue
}
Dr. R. Jothi, VIT Chennai
Front :
front rear
front_function(Q)
Before 9 2 5 1 8 {
0 1 2 3 4 5 6 7 8 9 return Q[front];
}
front rear
After 9 2 5 1 8
0 1 2 3 4 5 6 7 8 9
Linear Queue
b c j e f g i a
Waste of memory
0 1 2 3 4 5 6 7 8 9
0 1
rear
9 2 front
a b
Circular Queue 8 i c 3
g j
7 4
f e
Dr. R. Jothi, VIT Chennai
6 5
Circular Queue
front increases by (1 modulo Maxsize) 0 1
rear
after each dequeue( ): 9 2 front
front=front+1 % Maxsize a b
rear increases by (1 modulo capacity)
8 i c 3
after each enqueue( ):
rear=rear+1 % Maxsize g j
7
f e 4
6 5
8 i c 3
g j
7
f e 4
6 5
(rear+1)% Maxsize = (1+1) % 10 = 2 = front
Q[rear]=x;
}
8 3
7
4
6 5
rear = -1
front = -1
Dr. R. Jothi, VIT Chennai
Queue : C Implementation
}
Dr. R. Jothi, VIT Chennai
Circular Queue Applications
CPU Process scheduling
Memory Management