一. AcWing828_模拟栈

网页捕获_17-5-2023_17105_www.acwing.com.jpeg


二. 理论

  • 栈是 OI 中常用的一种线性数据结构,请注意,本文主要讲的是栈这种数据结构,而非程序运行时的系统栈/栈空间。
  • 栈的修改是按照后进先出的原则进行的,因此栈通常被称为是后进先出(last in first out)表,简称 LIFO 表。

三. 代码

#include<iostream>
#include<cstdio>
using namespace std;
namespace Question
{
    const int N=1e5+10;

    int m;
}
using namespace Question;

namespace Stack
{
    int stk[N], top;//数组模拟栈, 栈针
    
    void init()//初始化栈
    {
        top=0;
    }
    
    void pop()//栈顶出栈
    {
        top--;
    }
    
    void push(int x)//栈顶入栈
    {
        stk[++top]=x;
    }
    
    int top()//询问栈顶元素
    {
        return stk[top];
    }
    
    bool isEmpty()
    {
        return top<=0;
    }
}
using namespace Stack;

signed main()
{
    cin>>m;
    
    while(m--)
    {
        int x;
        char op[6];
        scanf("%s", op);
        
        if(op[0]=='p'&&op[1]=='u')
        {
            scanf("%d", &x);
            push(x);
        }
        else if(op[0]=='e')
        {
            if(isEmpty()) puts("YES");
            else puts("NO");
        }
        else if(op[0]=='q') printf("%d\n", top());
        else pop();
    }
}

四. cppSTL中的栈stack

  • 创建:stack stk
  • 返回栈顶:stk.top()
  • 插入传入的参数到栈顶:stk.push()
  • 弹出栈顶:stk.pop()
  • 返回是否为空:stk.empty()
  • 返回元素数量:stk.size()
  • 赋值:=