一、问题:acwing828 模拟栈
二、思路:
1.本文用栈操作来解决,栈的入栈,出栈,判空,查询栈顶元素等操作是我们需要牢牢记住的
2.栈的操作要点:
后进先出(想象成罐子,后放的东西能先拿出来)
只能在栈顶操作(入栈,出栈,查询栈顶元素)
三、解决问题:
1.STL
#include<iostream>
#include<stack>
using namespace std;
const int N = 100010;
stack<int> st;
int main()
{
int n;
cin>>n;
while(n -- )
{
string op;
cin>>op;
int x;
if(op=="push")
{
cin>>x;
st.push(x);
}
else if(op=="pop")
{
st.pop();
}
else if(op=="query")
{
cout<<st.top()<<endl;
}
else if(op=="empty")
{
if(st.empty())cout<<"YES";
else cout << "NO";
cout<<endl;
}
}
}
2.模拟栈
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int stack[N];
int top=-1;
void push()
{
int x;
cin>>x;
stack[++top]=x;
}
void pop()
{
top--;
}
void query()
{
if(top==-1)cout<<"你干嘛";
else cout<< stack[top]<<endl;
}
void empty()
{
if(top==-1)cout<<"YES";
else cout<<"NO";
cout<<endl;
}
void pick(string op)
{
if(op=="push")push();
else if(op=="pop")pop();
else if(op=="query")query();
else if(op=="empty")empty();
}
int main()
{
int n;
cin>>n;
while (n -- )
{
string op;
cin>>op;
pick(op);
}
}