模拟栈

实现一个栈,栈初始为空,支持四种操作:

  1. push x – 向栈顶插入一个数 xx;
  2. pop – 从栈顶弹出一个数;
  3. empty – 判断栈是否为空;
  4. 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;
}

  

posted @ 2022-11-30 21:57  !&&||  阅读(37)  评论(0)    收藏  举报