828. 模拟栈
828. 模拟栈
1、STL法
#include<iostream>
#include <vector>
using namespace std;
int main()
{
string op;
int m, x;
vector<int> stack;
cin >> m;
while(m--)
{
cin >> op;
if(op == "pop") {
stack.pop_back();
}
else if(op == "push") {
cin >> x;
stack.push_back(x);
}
else if(op == "empty") {
if(stack.size() == 0)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
else if(op == "query") //操作的查询结果为一个整数,表示栈顶元素的值。
cout << stack.back() << endl;
}
}
2、数组模拟栈
-
用top表示栈顶所在的索引。初始时,top = -1。表示没有元素。
-
push x :栈顶所在索引往后移动一格,然后放入x。st[++top] = x。
-
pop : top 往前移动一格。top–。
-
empty :top 大于等于 0 栈非空,小于 0 栈空。top == -1 ? “YES” : “NO”
-
query : 返回栈顶元素。st[top]
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int st[N];
int top = -1;
int main()
{
int n;
cin >> n;
while(n--)
{
string op;
int x;
cin >> op;
if(op == "push") {
cin >> x;
st[++top] = x;
}
else if(op == "pop") {
top--;
}
else if(op == "empty") {
cout << (top == -1 ? "YES" : "NO") << endl;//这里要加括号
}
else if(op == "query") {
cout << st[top] << endl;
}
}
}