栈
题目 模拟栈
思路分析
以0为起始位开始存 只在一端操作(仅用一个指针/下标维护当前可用位置)
用-1判空
代码实现
#include<bits/stdc++.h>
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;
}
}
return 0;
}
💬 评论