-
Notifications
You must be signed in to change notification settings - Fork 0
/
circular_queue.cpp
81 lines (67 loc) · 1.6 KB
/
circular_queue.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
using namespace std;
class CircularQueue{
int *arr;
int front;
int rear;
int size;
public:
CircularQueue(int n){
size = n;
arr = new int[n];
front = rear = -1;
}
bool enqueue(int value){
//to check whther queue is full
if( (front == 0 && rear == size-1) || (rear == (front-1)%(size-1) ) ) {
cout << "Queue is Full";
return false;
}
else if(front == -1) //first element to push
{
front = rear = 0;
}
else if(rear == size-1 && front != 0) {
rear = 0; //to maintain cyclic nature
}
else
{//normal flow
rear++;
}
//push inside the queue
arr[rear] = value;
return true;
}
int dequeue(){
if(front == -1){//to check queue is empty
cout << "Queue is Empty " << endl;
return -1;
}
int ans = arr[front];
arr[front] = -1;
if(front == rear) { //single element is present
front = rear = -1;
}
else if(front == size - 1) {
front = 0; //to maintain cyclic nature
}
else
{//normal flow
front++;
}
return ans;
}
};
int main()
{
CircularQueue cq(5);
cq.enqueue(2);
cq.enqueue(4);
cq.enqueue(6);
cq.enqueue(9);
cq.enqueue(1);
cq.dequeue();
cq.dequeue();
cq.enqueue(11);
cq.enqueue(7);
}