栈的基本操作

2:栈的基本操作

总时间限制: 
1000ms 
内存限制: 
1000kB
描述

栈是一种重要的数据结构,它具有push k和pop操作。push k是将数字k加入到栈中,pop则是从栈中取一个数出来。

栈是后进先出的:把栈也看成横向的一个通道,则push k是将k放到栈的最右边,而pop也是从栈的最右边取出一个数。

假设栈当前从左至右含有1和2两个数,则执行push 5和pop操作示例图如下:

          push 5          pop

栈   1 2  ------->  1 2 5 ------>  1 2

现在,假设栈是空的。给定一系列push k和pop操作之后,输出栈中存储的数字。若栈已经空了,仍然接收到pop操作,

则输出error。

输入
第一行为m,表示有m组测试输入,m<100。
每组第一行为n,表示下列有n行push k或pop操作。(n<150)
接下来n行,每行是push k或者pop,其中k是一个整数。
(输入保证同时在栈中的数不会超过100个)
输出
对每组测试数据输出一行。该行内容在正常情况下,是栈中从左到右存储的数字,数字直接以一个空格分隔,如果栈空,则不作输出;但若操作过程中出现栈已空仍然收到pop,则输出error。
样例输入
2
4
push 1
push 3
pop
push 5
1
pop
样例输出
1 5
error
  • #include<iostream>
    #include<cmath>
    #include<cstring>
    #include<algorithm>
    #include<iomanip>
    #include<queue>
    #include<stack>
    #include<vector>
    #include<set>
    #include<map>
    using namespace std;
    int m,n,t;
    string s;
    int a[105];
    int Top=0;
    int main()
    {
    	cin>>m;
    	while(m--)
    	{
    		cin>>n;
    		Top=0;
    		int flag=0;
    		while(n--) 
    		{
    			cin>>s;
    			if(flag)
    			{
    				if(s[1]=='u')
    				cin>>t;
    				continue;
    			}
    			if(s[1]=='u')
    			{
    				cin>>t;
    				a[Top++]=t;
    			}
    			else
    			{
    				if(Top>0)
    				{
    					--Top;
    				}
    				else
    				{
    					cout<<"error ";
    					flag=1;
    				}
    			}
    		}
    		if(flag==0)
    		for(int i=0;i<Top;++i)
    		{
    			cout<<a[i]<<" ";
    		}
    		cout<<endl;
    	}
    	return 0;
    }


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值