数组模拟栈

题目

代码

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int stack[N], tt;

void push_stack(int x)
{
    stack[++tt] = x;
}
void pop_stack()
{
    tt--;
}
int empty_stack()
{ // 返回1则为空,0则不为空。
    return tt == 0;
}
int top_stack()
{
    return stack[tt];
}
int main()
{
    int m;
    cin >> m;
    while (m--)
    {
        string str;
        cin >> str;
        if (str == "push")
        {
            int x;
            cin >> x;
            push_stack(x);
        }
        else if (str == "pop")
        {
            pop_stack();
        }
        else if (str == "empty")
        {
            if (empty_stack())
            {
                cout << "YES" << endl;
            }
            else
            {
                cout << "NO" << endl;
            }
        }
        else
        {
            cout << top_stack() << endl;
        }
    }

    return 0;
}
posted @ 2025-02-27 16:33  electricity111  阅读(23)  评论(0)    收藏  举报