数组模拟栈

2362471311mars / 2024-02-08 / 原文

数组模拟栈:

值得注意的是:栈中tt从0开始
这一点区别于队列

AcWing对应题目[https://www.acwing.com/problem/content/830/]

#include<iostream>
#include<stdio.h>
using namespace std;
const int N=100010;
int skt[N],tt=0;//栈从0开始
//入栈
void push(int n)
{
    skt[++tt]=n;
}
//出栈
void pop()
{
    tt--;
}
//判🈳
bool empty()
{
    if(tt==0)
    {
        return true;
    }
    else{
        return false;
    }

}
int query()//查询栈顶元素
{
    return skt[tt];
}
int main()
{
    int n;
    scanf("%d",&n);
    while(n--)
    {
        string str;
        int num;
        cin>>str;
        if(str=="push")
        {

        scanf("%d",&num);
            push(num);
        }
        if(str=="pop")
        {
            pop();
        }
        if(str=="empty")
        {
           if(empty())
           {
            printf("YES\n");
           }
           else{
            printf("NO\n");
           }

        }
        if(str=="query")
        {
            printf("%d\n",query());
        }
    }
}