-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathqueueClass.cpp
More file actions
82 lines (68 loc) · 1.42 KB
/
queueClass.cpp
File metadata and controls
82 lines (68 loc) · 1.42 KB
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
#include <iostream>
#include <climits>
using namespace std;
template <typename T>
class Queue {
T *arr;
int head, tail;
int sz;
int capacity;
public:
Queue(int capacity = 10) {
this->capacity = capacity;
sz = 0;
head = 0;
tail = 0;
arr = new T[capacity];
}
int size() {
return sz;
}
bool empty() {
return sz == 0;
}
bool full() {
return sz == capacity;
}
void resize(int cap) {
if(cap < 1) cap = 1;
T* narr = new T[cap];
for(int i=0; i<sz; i++)
narr[i] = arr[(head + i) % capacity];
delete []arr;
arr = narr;
capacity = cap;
}
void enqueue(T value) {
if (full()) {
resize(2 * capacity);
}
arr[tail] = value;
tail = (tail + 1) % capacity;
sz++;
}
T dequeue() {
if(empty()) {
throw std::underflow_error("Queue is empty");
}
T val = arr[head];
head = (head + 1) % capacity;
sz--;
return val;
}
T front() {
if(empty()) {
throw std::underflow_error("Queue is empty");
}
return arr[head];
}
void display() {
for(int i=0; i<sz; i++) {
cout << arr[(head + i) % capacity] << " ";
}
cout << endl;
}
~Queue() {
delete []arr;
}
};