-
Notifications
You must be signed in to change notification settings - Fork 256
/
Copy path04 C++ Circular Queue.cpp
107 lines (88 loc) · 1.82 KB
/
04 C++ 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
using namespace std;
class CircularQueue {
private:
int size;
int front;
int rear;
int* Q;
public:
CircularQueue(int size);
~CircularQueue();
bool isFull();
bool isEmpty();
void enqueue(int x);
int dequeue();
void display();
};
CircularQueue::CircularQueue(int size) {
this->size = size;
front = 0;
rear = 0;
Q = new int[size];
}
CircularQueue::~CircularQueue() {
delete[] Q;
}
bool CircularQueue::isEmpty() {
if (front == rear) {
return true;
}
return false;
}
bool CircularQueue::isFull() {
if ((rear + 1) % size == front) {
return true;
}
return false;
}
void CircularQueue::enqueue(int x) {
if (isFull()) {
cout << "Queue Overflow" << endl;
}
else {
rear = (rear + 1) % size;
Q[rear] = x;
}
}
int CircularQueue::dequeue() {
int x = -1;
if (isEmpty()) {
cout << "Queue Underflow" << endl;
}
else {
front = (front + 1) % size;
x = Q[front];
}
return x;
}
void CircularQueue::display() {
int i = front + 1;
do {
cout << Q[i] << flush;
if (i < rear) {
cout << " <- " << flush;
}
i = (i + 1) % size;
} while (i != (rear + 1) % size);
}
int main() {
int A[] = { 1, 3, 5, 7, 9 };
CircularQueue cq(sizeof(A) / sizeof(A[0]) + 1);
// Enqueue
for (int i = 0; i < sizeof(A) / sizeof(A[0]); i++) {
cq.enqueue(A[i]);
}
// Display
cq.display();
cout << endl;
// Overflow
cq.enqueue(10);
// Dequeue
for (int i = 0; i < sizeof(A) / sizeof(A[0]); i++) {
cq.dequeue();
}
// Underflow
cq.dequeue();
return 0;
}