前序知识
数组模拟栈: 用top表示栈顶所在的索引。初始时,top = -1。表示没有元素。
push x:栈顶所在索引往后移动一格,然后放入x。st[++top] = x。
pop : top 往前移动一格。top–。
empty :top大于等于 0 栈非空,小于 0 栈空。top == -1 ? “YES” : “NO”
query : 返回栈顶元素。st[top]
题目描述
代码展示
#include <iostream>
using namespace std;
const int N = 100010;
int st[N];
int top = -1;
int n;
int main()
{
cin >> n;
while(n--)
{
string s;
cin >> s;
//栈顶所在索引往后移动一格,然后放入x。
if(s == "push")
{
int a;
cin >> a;
st[++top] = a;
}
//往前移动一格
if(s == "pop")
{
top --;
}
//返回栈顶元素
if(s == "query")
{
cout << st[top] << endl;
}
//大于等于 0 栈非空,小于 0 栈空
if(s == "empty")
{
cout << (top == -1 ? "YES" : "NO") << endl;
}
}
}
参考链接: AcWing 828. 模拟栈—代码详解