1// Circular Queue implementation in C++
2
3#include <iostream>
4#define SIZE 5 /* Size of Circular Queue */
5
6using namespace std;
7
8class Queue {
9 private:
10 int items[SIZE], front, rear;
11
12 public:
13 Queue() {
14 front = -1;
15 rear = -1;
16 }
17 // Check if the queue is full
18 bool isFull() {
19 if (front == 0 && rear == SIZE - 1) {
20 return true;
21 }
22 if (front == rear + 1) {
23 return true;
24 }
25 return false;
26 }
27 // Check if the queue is empty
28 bool isEmpty() {
29 if (front == -1)
30 return true;
31 else
32 return false;
33 }
34 // Adding an element
35 void enQueue(int element) {
36 if (isFull()) {
37 cout << "Queue is full";
38 } else {
39 if (front == -1) front = 0;
40 rear = (rear + 1) % SIZE;
41 items[rear] = element;
42 cout << endl
43 << "Inserted " << element << endl;
44 }
45 }
46 // Removing an element
47 int deQueue() {
48 int element;
49 if (isEmpty()) {
50 cout << "Queue is empty" << endl;
51 return (-1);
52 } else {
53 element = items[front];
54 if (front == rear) {
55 front = -1;
56 rear = -1;
57 }
58 // Q has only one element,
59 // so we reset the queue after deleting it.
60 else {
61 front = (front + 1) % SIZE;
62 }
63 return (element);
64 }
65 }
66
67 void display() {
68 // Function to display status of Circular Queue
69 int i;
70 if (isEmpty()) {
71 cout << endl
72 << "Empty Queue" << endl;
73 } else {
74 cout << "Front -> " << front;
75 cout << endl
76 << "Items -> ";
77 for (i = front; i != rear; i = (i + 1) % SIZE)
78 cout << items[i];
79 cout << items[i];
80 cout << endl
81 << "Rear -> " << rear;
82 }
83 }
84};
85
86int main() {
87 Queue q;
88
89 // Fails because front = -1
90 q.deQueue();
91
92 q.enQueue(1);
93 q.enQueue(2);
94 q.enQueue(3);
95 q.enQueue(4);
96 q.enQueue(5);
97
98 // Fails to enqueue because front == 0 && rear == SIZE - 1
99 q.enQueue(6);
100
101 q.display();
102
103 int elem = q.deQueue();
104
105 if (elem != -1)
106 cout << endl
107 << "Deleted Element is " << elem;
108
109 q.display();
110
111 q.enQueue(7);
112
113 q.display();
114
115 // Fails to enqueue because front == rear + 1
116 q.enQueue(8);
117
118 return 0;
119}