-
Notifications
You must be signed in to change notification settings - Fork 0
/
CircularQueue.cpp
84 lines (78 loc) · 1.74 KB
/
CircularQueue.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
#include <iostream>
#define MAX 3
using namespace std;
template <class T>
class Queue
{
private:
int front, rear;
T q[MAX];
public:
Queue() // Initialize Queue
{
front = -1;
rear = -1;
}
// Enqueue Elements
void enqueue(T x)
{
if (front == -1 && rear == -1) // Empty Queue
{
front = rear = 0;
q[rear] = x;
cout << x << " Enqueued!" << endl;
}
else if (front == ((rear + 1) % MAX)) // Full Queue
{
cout << "Queue is Full! Cannot Enqueue " << x << endl;
}
else // Normal Case
{
rear = ((rear + 1) % MAX);
q[rear] = x;
cout << x << " Enqueued!" << endl;
}
}
// Dequeue Elements
void dequeue()
{
if (front == -1 && rear == -1) // Empty Queue
{
cout << "Queue is Empty! Nothing to Dequeue!" << endl;
}
else if (rear == front) // One Element Left
{
cout << q[front] << " Dequeued!" << endl;
front = rear = -1;
}
else
{
cout << q[front] << " Dequeued!" << endl;
front = (front + 1) % MAX;
}
}
// Peek Front Element
T peek()
{
if (front != -1)
return q[front];
else
{
cout << "Nothing at the Front!" << endl;
}
}
};
int main()
{
system("cls");
Queue<int> q;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.dequeue();
q.dequeue();
q.enqueue(5);
cout << "Element at front right now is:" << q.peek() << endl;
return 0;
}