-
Notifications
You must be signed in to change notification settings - Fork 1
/
circular_queue.cpp
119 lines (117 loc) · 2.27 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
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
108
109
110
111
112
113
114
115
116
117
118
119
#include <bits/stdc++.h>
using namespace std;
class QueueFullException : public exception
{
virtual const char *what() const throw()
{
return "\nQueue is full\n";
}
};
class QueueEmptyException : public exception
{
virtual const char *what() const throw()
{
return "\nQueue is empty\n";
}
};
//generic implementation of Circular Queue data structure using templates
template <class T>
class Circular_Queue
{
private:
static const int MAX = 3;
T data[MAX];
int front, rear;
public:
Circular_Queue()
{
rear = front = -1;
}
void Enqueue(const T element)
{
if ((front == 0 && rear == MAX - 1) || (front == rear + 1))
{
QueueFullException e;
throw e;
}
if (front == -1)
{
front = 0;
rear = 0;
}
else
{
if (rear == MAX - 1)
rear = 0;
else
rear++;
}
data[rear] = element;
}
T Dequeue()
{
if (front == -1)
{
QueueEmptyException e;
throw e;
}
T deleted = data[front];
if (front == rear)
{
front = -1;
rear = -1;
}
else
{
if (front == MAX - 1)
front = 0;
else
front++;
}
return deleted;
}
T Front()
{
if (isEmpty())
{
QueueEmptyException e;
throw e;
}
else
{
return data[front];
}
}
int Size()
{
if (front <= rear)
return rear - front + 1;
else
return MAX + rear - front + 1;
}
bool isEmpty()
{
return (front == -1);
}
};
int main()
{
Circular_Queue<int> q;
if (q.isEmpty())
{
cout << "Queue is empty" << endl;
}
// Enqueue elements
q.Enqueue(100);
q.Enqueue(200);
q.Enqueue(300);
// Size of queue
cout << "Size of queue = " << q.Size() << endl;
// Front element
cout << q.Front() << endl;
// Dequeue elements
cout << q.Dequeue() << endl;
cout << q.Dequeue() << endl;
cout << q.Dequeue() << endl;
return 0;
}