Circular Queues and
Implementation with Array
Array Implementation
2
5 4 6 7 8 7 6
0 1 2 3 4 5 6 7 8
Front=0
Rear=6
8 7 6
0 1 2 3 4 5 6 7 8
Front=4
Rear=6
7 6 12 67
0 1 2 3 4 5 6 7 8
Front=5
Rear=8
How can we insert more elements? Rear index can
not move beyond the last element….
Solution: Using circular queue
 Allow rear to wrap around the array.
if(rear == queueSize-1)
rear = 0;
else
rear++;
 Or use modulo arithmetic
rear = (rear + 1) % queueSize;
3
Enqueing in a Circular Queue
4
7 6 12 67
0 1 2 3 4 5 6 7 8
Front=5
Rear=8
Enqueue 39 Rear=(Rear+1) mod Queue Size = (8+1) mod 9 = 0
39 7 6 12 67
0 1 2 3 4 5 6 7 8
Front=5
Rear=0
5
EMPTY QUEUE
[2] [3] [2] [3]
[1] [4] [1] [4]
[0] [5] [0] [5]
front = 0 front = 0
rear = 0 rear = 3
J2
J1
J3
Implementation 2: Wrapped Configuration
Can be seen as a circular queue
How to determine empty and full
Queues?
6
FULL QUEUE FULL QUEUE
[2] [3] [2] [3]
[1] [4][1] [4]
[0] [5] [0] [5]
front =0
rear = 5
front =4
rear =3
J2 J3
J1 J4
J5 J6 J5
J7
J8 J9
Leave one empty
space when queue
is full
Why?
How to test when queue is empty?
How to test when queue is full?
How to determine empty and full
Queues?
 Number of approaches
A counter indicating number of values in the
queue can be used (We will use this
approach)
Comparing the Rear and the Front of the
Queue
7

Lec-12, 13 Quees - Circular Queues and Implementation with Array

  • 1.
  • 2.
    Array Implementation 2 5 46 7 8 7 6 0 1 2 3 4 5 6 7 8 Front=0 Rear=6 8 7 6 0 1 2 3 4 5 6 7 8 Front=4 Rear=6 7 6 12 67 0 1 2 3 4 5 6 7 8 Front=5 Rear=8 How can we insert more elements? Rear index can not move beyond the last element….
  • 3.
    Solution: Using circularqueue  Allow rear to wrap around the array. if(rear == queueSize-1) rear = 0; else rear++;  Or use modulo arithmetic rear = (rear + 1) % queueSize; 3
  • 4.
    Enqueing in aCircular Queue 4 7 6 12 67 0 1 2 3 4 5 6 7 8 Front=5 Rear=8 Enqueue 39 Rear=(Rear+1) mod Queue Size = (8+1) mod 9 = 0 39 7 6 12 67 0 1 2 3 4 5 6 7 8 Front=5 Rear=0
  • 5.
    5 EMPTY QUEUE [2] [3][2] [3] [1] [4] [1] [4] [0] [5] [0] [5] front = 0 front = 0 rear = 0 rear = 3 J2 J1 J3 Implementation 2: Wrapped Configuration Can be seen as a circular queue
  • 6.
    How to determineempty and full Queues? 6 FULL QUEUE FULL QUEUE [2] [3] [2] [3] [1] [4][1] [4] [0] [5] [0] [5] front =0 rear = 5 front =4 rear =3 J2 J3 J1 J4 J5 J6 J5 J7 J8 J9 Leave one empty space when queue is full Why? How to test when queue is empty? How to test when queue is full?
  • 7.
    How to determineempty and full Queues?  Number of approaches A counter indicating number of values in the queue can be used (We will use this approach) Comparing the Rear and the Front of the Queue 7

Editor's Notes

  • #4 Visit: tshahab.blogspot.com
  • #5 Visit: tshahab.blogspot.com
  • #6 Visit: tshahab.blogspot.com