-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqueue.cpp
executable file
·106 lines (99 loc) · 1.85 KB
/
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
#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 standard Queue data structure using templates
template <class T>
class Queue
{
private:
static const int MAX_SIZE = 100;
T data[MAX_SIZE];
int front, rear;
public:
Queue()
{
front = 0;
rear = 0;
}
void Enqueue(const T element)
{
if (Size() == MAX_SIZE - 1)
{
QueueFullException e;
throw e;
}
else
{
data[rear] = element;
rear = ++rear % MAX_SIZE;
}
}
T Dequeue()
{
if (isEmpty())
{
QueueEmptyException e;
throw e;
}
else
{
T ret = data[front];
front = ++front % MAX_SIZE;
return ret;
}
}
T Front()
{
if (isEmpty())
{
QueueEmptyException e;
throw e;
}
else
{
return data[front];
}
}
int Size()
{
return abs(rear - front);
}
bool isEmpty()
{
return (front == rear);
}
};
int main()
{
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;
}