题目描述
实现一个栈,队列初始为空,支持四种操作:
(1) “push x” – 向栈顶插入一个数x;
(2) “pop” – 从栈顶弹出一个数;
(3) “empty” – 判断栈是否为空;
(4) “query” – 查询栈顶元素。
现在要对栈进行M个操作,其中的每个操作3和操作4都要输出相应的结果。
输入格式
第一行包含整数M,表示操作次数。
接下来M行,每行包含一个操作命令,操作命令为”push x”,”pop”,”empty”,”query”中的一种。
输出格式
对于每个”empty”和”query”操作都要输出一个查询结果,每个结果占一行。
其中,”empty”操作的查询结果为“YES”或“NO”,”query”操作的查询结果为一个整数,表示队头元素的值。
数据范围
1≤M≤100000,
1≤x≤109,
所有操作保证合法。
样例
输入样例:
10
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6
输出样例:
NO
6
YES
4
直接一个模拟就可以过了呀写那摸多代码干什么? 模拟方案1 c++代码
include[HTML_REMOVED]
using namespace std;
const int M=100010;
int stk[M],tt=0;
int m;
int main()
{
cin>>m;int x;string s1;
for(int i;i<=m;i)
{
cin>>s1;
if(s1==”push”)
{
cin>>x;
stk[tt]=x;
}
else if(s1==”pop”)
{
tt–;
}
else if(s1==”empty”)
{
if(tt>0) cout<<”NO”<<endl;
else cout<<”YES”<<endl;
}
else if(s1==”query”)
{
cout<<stk[tt]<<endl;
}
}
return 0;
}
但是for循环看起来好慢啊就有了第二种方法
include[HTML_REMOVED]
using namespace std;
const int M=100010;
int stk[M],tt=0;
int m;
int main()
{
cin>>m;int x;string s1;
while(m–)
{
cin>>s1;
if(s1==”push”)
{
cin>>x;
stk[++tt]=x;
}
else if(s1==”pop”) tt–;
else if(s1==”empty”)
{
if(tt>0) cout<<”NO”<<endl;
else cout<<”YES”<<endl;
}
else if(s1==”query”) cout<<stk[tt]<<endl;
}
return 0;
}
可不可以用三目运算让代码更简便呢?
include[HTML_REMOVED]
using namespace std;
const int M=100010;
int stk[M],tt=0;
int m;
int main()
{
cin>>m;int x;string s1;
while(m–)
{
cin>>s1;
if(s1==”push”)
{
cin>>x;
stk[++tt]=x;
}
else if(s1==”pop”) tt–;
else if(s1==”empty”) cout<<(tt ? “NO” : “yes”)<<endl;
else if(s1==”query”) cout<<stk[tt]<<endl;
}
return 0;
}
这样一个完美的代码就出来了
注:代码内含有中文字符(直接交是不可能过的)请自行修改。