九度oj 题目1108:堆栈的使用

题目描述:

    堆栈是一种基本的数据结构。堆栈具有两种基本操作方式,push 和 pop。Push一个值会将其压入栈顶,而 pop 则会将栈顶的值弹出。现在我们就来验证一下堆栈的使用。

输入:

     对于每组测试数据,第一行是一个正整数 n,0<n<=10000(n=0 结束)。而后的 n 行,每行的第一个字符可能是'P’或者'O’或者'A’;如果是'P’,后面还会跟着一个整数,表示把这个数据压入堆栈;如果是'O’,表示将栈顶的值 pop 出来,如果堆栈中没有元素时,忽略本次操作;如果是'A’,表示询问当前栈顶的值,如果当时栈为空,则输出'E'。堆栈开始为空。

输出:

    对于每组测试数据,根据其中的命令字符来处理堆栈;并对所有的'A’操作,输出当时栈顶的值,每个占据一行,如果当时栈为空,则输出'E’。当每组测试数据完成后,输出一个空行。

样例输入:
3
A
P 5
A
4
P 3
P 6
O 
A
0
样例输出:
E
5

3

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cstring>
 4 #include <iostream>
 5 #include <algorithm>
 6 #include <cmath>
 7 #include <stack>
 8 #define MAX 102
 9 using namespace std;
10  
11 stack <int> temp;
12 
13 int main(int argc, char const *argv[])
14 {
15     int n;
16     //freopen("input.txt","r",stdin);
17     while(scanf("%d",&n) != EOF && n != 0) {
18         char opt;
19         int tmp;
20         int ptr = 0;
21         while(n--) {
22             cin >> opt;
23             if(opt == 'P') {
24                scanf("%d",&tmp);
25                temp.push(tmp);
26                
27             }
28             else if(opt == 'O') {
29               if(!temp.empty()) {
30                 temp.pop();
31               }
32               
33             }
34             else if(opt == 'A') {
35                if(temp.empty()) {
36                   puts("E");
37                }
38                else {
39                   printf("%d
",temp.top());
40                }
41             }
42         }
43         puts("");
44         while(!temp.empty()) {
45             temp.pop();
46         }
47 
48     }
49     return 0;
50 }
 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <cmath>
 6 #include <stack>
 7 #include <iostream>
 8 #define MAX 1000002
 9 using namespace std;
10   
11 int temp[MAX];
12 int main(int argc, char const *argv[])
13 {
14     int n;
15     //freopen("input.txt","r",stdin);
16     while(scanf("%d",&n) != EOF && n != 0) {
17         char opt;
18         int tmp;
19         int ptr = 0;
20         while(n--) {
21             cin >> opt;
22             if(opt == 'P') {
23                scanf("%d",&tmp);
24                temp[++ptr] = tmp;
25                 
26             }
27             else if(opt == 'O') {
28               if(ptr != 0)
29                ptr--;
30             }
31             else if(opt == 'A') {
32                if(ptr == 0) {
33                   puts("E");
34                }
35                else {
36                   printf("%d
",temp[ptr]);
37                }
38             }
39         }
40         puts("");
41     }
42     return 0;
43 }

注意:如果是'O’,表示将栈顶的值 pop 出来,如果堆栈中没有元素时,忽略本次操作

原文地址:https://www.cnblogs.com/jasonJie/p/5775803.html