水题,直接用stl的vector模拟stack即可。
#include<bits/stdc++.h>
using i64 = long long;
class stack {
std::vector<int> a;
public:
stack() {}
void push(int x) {
a.push_back(x);
}
void pop() {
if (a.empty()) {
std::cout << "error\n";
return;
}
std::cout << a.back() << "\n";
a.pop_back();
}
void top() {
if (a.empty()) {
std::cout << "error\n";
return;
}
std::cout << a.back() << "\n";
}
};
int main() {
std::cin.tie(nullptr)->sync_with_stdio(false);
stack stk;
int n;
std::cin >> n;
while (n--) {
std::string op;
std::cin >> op;
if (op == "push") {
int x;
std::cin >> x;
stk.push(x);
} else if (op == "pop") {
stk.pop();
} else {
stk.top();
}
}
return 0;
}

京公网安备 11010502036488号