您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法MOOC / 第三章 栈与队列 练习题 2:栈的基本操作

2014-11-04 08:15 351 查看

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<stdio.h> #include<stack> #include<math.h> #include<string.h> #include<iostream> #include<algorithm> using namespace std; stack<int >q; stack<int >q1; int main() { int n,m; char a[1000]; scanf("%d",&n); while(n--) { int f=0; int f1=0; int g=0; scanf("%d",&m); while(m--) { int t; scanf("%s",a); if(strcmp(a,"push")==0) { scanf("%d",&t); if(g==0) { q.push(t); f++; } } if(strcmp(a,"pop")==0) { if(f==0) { g=1; } else { if(g!=1) { q.pop(); f--; } } } } if(g==1) printf("error\n"); else { if(f==0) continue; else { while(!q.empty()) { q1.push(q.top()); q.pop(); } while(!q1.empty()) { if(f1==0) { printf("%d",q1.top()); f1=1; } else printf(" %d",q1.top()); q1.pop(); } printf("\n"); } } } return 0; }


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: