题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include<iostream>
#include<string>
using namespace std;
const int N = 100000;
int main() {
int stk[N], tt = 0;//tt表示栈顶
int n, x;
string sb;
cin >> n;
while (n--) {
cin >> sb;
if (sb == "push") {
cin >> x;
stk[++tt] = x;//向栈顶插入一个数
}
if (sb == "pop") {
if (tt <= 0) {//判断栈是否为空,如果tt>0,则表示不为空
cout << "error" << endl;
continue;
}
cout << stk[tt] << endl;
tt--;//从栈顶弹出一个数
}
if (sb == "top") {
if (tt <= 0) {
cout << "error" << endl;
continue;
}
cout << stk[tt] << endl;
}
}
return 0;
}
查看14道真题和解析
安克创新 Anker公司福利 659人发布