模拟栈
实现一个栈,栈初始为空,支持四种操作:
push x– 向栈顶插入一个数 xx;pop– 从栈顶弹出一个数;empty– 判断栈是否为空;query– 查询栈顶元素。
现在要对栈进行 M 个操作,其中的每个操作 3 和操作 4 都要输出相应的结果
#include <iostream>
#include <cstring>
using namespace std;
const int N = 100010;
int stk[N];
int tt;
int main() {
int n;
scanf ("%d", &n);
while (n--) {
char ch[7];
scanf ("%s", ch);
if (strcmp(ch, "push") == 0) {
int x;
scanf ("%d", &x);
stk[++tt] = x;
}
else if ( strcmp(ch, "pop") == 0) {
tt--;
}
else if ( strcmp(ch, "empty") == 0) {
if (tt) puts("NO");
else puts("YES");
}
else {
printf ("%d\n", stk[tt]);
}
}
return 0;
}

浙公网安备 33010602011771号