95 lines
1.9 KiB
C++
95 lines
1.9 KiB
C++
#include <iostream>
|
|
#include <limits>
|
|
using namespace std;
|
|
|
|
template <class T>
|
|
class Queue {
|
|
private:
|
|
T* element;
|
|
int begin;
|
|
int end;
|
|
int capacity;
|
|
|
|
public:
|
|
static constexpr T INF = numeric_limits<T>::max();
|
|
|
|
Queue(int len) : begin(0), end(0), capacity(len) {
|
|
element = new T[len];
|
|
}
|
|
|
|
~Queue() {
|
|
delete[] element;
|
|
}
|
|
|
|
void push(const T& e) {
|
|
if (end == capacity) {
|
|
int newCap = capacity * 2;
|
|
T* tmp = new T[newCap];
|
|
for (int i = begin; i < end; i++) {
|
|
tmp[i - begin] = element[i];
|
|
}
|
|
end -= begin;
|
|
begin = 0;
|
|
capacity = newCap;
|
|
delete[] element;
|
|
element = tmp;
|
|
}
|
|
element[end++] = e;
|
|
}
|
|
|
|
void pop() {
|
|
if (empty()) throw std::invalid_argument("Queue is empty.");
|
|
begin++;
|
|
}
|
|
|
|
T& front() {
|
|
if (empty()) throw std::invalid_argument("Queue is empty.");
|
|
return element[begin];
|
|
}
|
|
|
|
T& back() {
|
|
if (empty()) throw std::invalid_argument("Queue is empty.");
|
|
return element[end - 1];
|
|
}
|
|
|
|
bool empty() const {
|
|
return begin == end;
|
|
}
|
|
|
|
int size() const {
|
|
return end - begin;
|
|
}
|
|
};
|
|
|
|
int main() {
|
|
int n;
|
|
cin >> n;
|
|
Queue<int> q(n);
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
int p;
|
|
cin >> p;
|
|
switch (p) {
|
|
case 0: {
|
|
if (q.empty()) {
|
|
cout << "invalid" << endl;
|
|
} else {
|
|
cout << q.front() << endl;
|
|
q.pop();
|
|
}
|
|
break;
|
|
}
|
|
case 1: {
|
|
int val;
|
|
cin >> val;
|
|
q.push(val);
|
|
break;
|
|
}
|
|
default: {
|
|
return 0;
|
|
}
|
|
}
|
|
}
|
|
return 0;
|
|
}
|