AcWing 828. 模拟栈 C++
原题链接
简单
作者:
LaChimere
,
2021-05-15 12:12:21
,
所有人可见
,
阅读 222
C++
#include <iostream>
using namespace std;
class Stack {
public:
Stack(int M) : st_(new int[M]()), top_(-1), capacity_(M) {}
~Stack() {
delete [] st_;
}
bool push(int x) {
if (top_ == capacity_ - 1) {
return false;
}
st_[++top_] = x;
return true;
}
bool pop() {
if (top_ == -1) {
return false;
}
--top_;
return true;
}
bool empty() const {
return top_ == -1;
}
int query() const {
if (empty()) {
return -1;
}
return st_[top_];
}
private:
int *st_;
int top_;
int capacity_;
};
int main() {
int M, x;
string op;
cin >> M;
Stack st(M);
while (M--) {
cin >> op;
if (op == "push") {
cin >> x;
st.push(x);
} else if (op == "pop") {
st.pop();
} else if (op == "empty") {
if (st.empty()) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
} else {
cout << st.query() << endl;
}
}
return 0;
}