CODEVS 3139 栈练习3
【题目描述 Description】
比起第一题,本题加了另外一个操作,访问栈顶元素(编号3,保证访问栈顶元素时或出栈时栈不为空),现在给出这N此操作,输出结果。【输入描述 Input Description】
N
N次操作(1入栈 2出栈 3访问栈顶)
【输出描述 Output Description】
K行(K为输入中询问的个数)每次的结果
【样例输入 Sample Input】
6
1 7
3
2
1 9
1 7
3
【样例输出 Sample Output】
7
7
【数据范围及提示 Data Size & Hint】
对于50%的数据 N≤1000 入栈元素≤200
对于100%的数据 N≤100000入栈元素均为正整数且小于等于10^4
【题解】
本来很简单的题,纯模拟
但测试数据有坑
如果无任何输出,则在最后输出栈顶元素
需要特判
代码如下:
#include<cstdio>
#include<stack>
using namespace std;
stack<int>q;
int main()
{
bool fl=0;
int ok;
int n;int a;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&ok);
if(ok==1)
{
scanf("%d",&a);
q.push(a);
}
if(ok==2)
{
q.pop() ;
}
if(ok==3)
{
printf("%d\n",q.top() );
fl=1;
}
}
if(!fl)
{
printf("%d",q.top());
}
return 0;
}