-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue_circularArray.cpp
More file actions
103 lines (89 loc) · 2.12 KB
/
Copy pathqueue_circularArray.cpp
File metadata and controls
103 lines (89 loc) · 2.12 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* 2019.7.4
* data structure implementation - queue_circularArray
*/
#include <iostream>
#include <string>
using namespace std;
#define endl '\n'
class QueueCirArr {
public:
int q_size, capacity;
int first, last;
int *queue;
QueueCirArr() {
q_size = 0;
capacity = 8;
first = 0;
last = 0;
queue = new int[capacity];
}
~QueueCirArr() {}
void push(int value) {
if (q_size == capacity) {
capacity *= 2;
int *temp = new int[capacity];
for (int i = 0; i < capacity / 2; i++) {
temp[i] = queue[i];
}
queue = temp;
if (last < first)
last = first + q_size - 1;
}
queue[last] = value;
last = (last + 1) % (capacity + 1);
q_size++;
}
int front() {
if (q_size == 0) return -1;
return queue[first];
}
int back() {
if (q_size == 0) return -1;
return queue[(last - 1) % (capacity + 1)];
}
void pop() {
if (q_size == 0) return;
q_size--;
first = (first + 1) % (capacity + 1);
}
bool empty() {
return !q_size;
}
int size() {
return q_size;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
QueueCirArr queue;
int a;
cin >> a;
for (int i = 0; i < a; i++) {
string input;
cin >> input;
if (input == "push") {
int a;
cin >> a;
queue.push(a);
} else if (input == "pop") {
if (queue.empty())
cout << -1 << endl;
else cout << queue.front() << endl;
queue.pop();
} else if (input == "size")
cout << queue.size() << endl;
else if (input == "empty") {
if (queue.empty())
cout << 1 << endl;
else
cout << 0 << endl;
} else if (input == "front")
cout << queue.front() << endl;
else if (input == "back")
cout << queue.back() << endl;
}
return 0;
}