-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathqueue_arrays.cpp
More file actions
81 lines (70 loc) · 1.66 KB
/
queue_arrays.cpp
File metadata and controls
81 lines (70 loc) · 1.66 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
#include <iostream>
template <typename T>
class Queue {
T *data;
int size;
int firstIndex;
int nextIndex;
int capacity;
public:
Queue(int dataSize) {
data = new T[dataSize];
size = 0;
firstIndex = -1;
nextIndex = 0;
capacity = dataSize;
}
int getSize() {
return size;
}
bool isEmpty() {
return size == 0;
}
// Inserting an element
void enqueue(T element) {
if (size == capacity) {
T *newData = new T[capacity*2];
int j = 0;
for (int i = firstIndex; i < capacity; i++, j++) {
newData[j] = data[i];
}
for (int i = 0; i < firstIndex; i++, j++) {
newData[j] = data[i];
}
delete [] data;
data = newData;
firstIndex = 0;
nextIndex = capacity;
capacity *= 2;
}
data[nextIndex] = element;
nextIndex = (nextIndex + 1) % 5;
if (firstIndex == -1) {
firstIndex = 0;
}
size++;
}
// Getting the first element
T front() {
if (size == 0) {
std::cout << "Queue is empty!" << std::endl;
return 0;
}
return data[firstIndex];
}
// Removing an element
T dequeue() {
if (size == 0) {
std::cout << "Queue is empty!" << std::endl;
return 0;
}
T element = data[firstIndex];
firstIndex = (firstIndex + 1) % 5;
size--;
if (size == 0) {
firstIndex = -1;
nextIndex = 0;
}
return element;
}
};