入栈和出栈

来源:互联网 发布:iphone电话备份软件 编辑:程序博客网 时间:2024/05/01 02:03

Description

假设有一组数,共n个,如23、45、17、93、27、6、91、13,依次入栈(23最先入栈,13最后出栈),给定这n个数入栈和出栈的操作序列(push表示入栈,pop表示出栈),要求输出这n个数的出栈顺序。

例如,假设入栈和出栈的操作序列为:
push pop push push pop push pop push pop pop push push push pop pop pop

则这8个数的出栈顺序为:
23 17 93 27 45 13 91 6

Input

输入文件中包含多个测试数据。每个测试数据第一行为一个自然数n,2≤n≤20,表示有n个正整数;第2行为n个正整数,用空格隔开;第3行为操作序列,也是用空格隔开。输入文件最后一行为0,表示输入结束。

输入数据确保每个测试数据的操作序列不会出现栈为空时执行pop操作。

Output

对输入文件中的每个测试数据,输出n个正整数的出栈顺序,相邻两个正整数之间用空格隔开。

Sample Input

823 45 17 93 27 6 91 13push pop push push pop push pop push pop pop push push push pop pop pop0

Sample Output

23 17 93 27 45 13 91 6



简单的栈的应用,用个string来标记是入栈还是出栈,然后控制输出即可,


#include<stdio.h>#include<string.h>#include<string>#include<iostream>#include<stack>#include<algorithm>using namespace std;int main(){stack<int>op;int n;int i,k;int s[30];string st1,st2="push",st4="0";while(cin>>n){if(n==0)  break;int q=0;int t=0;for(i=0;i<n;i++){scanf("%d",&s[i]);}i=0;while(t<n){cin>>st1;if(st1==st2){op.push(s[i++]);}else{if(q==0){q=1;t++;printf("%d",op.top());op.pop();}else {t++;printf(" %d",op.top());op.pop();}}}printf("\n");}return 0;}


0 0
原创粉丝点击