栈(裸题)

本文介绍了一种使用栈数据结构解决后缀表达式计算的方法。文章详细解释了如何通过读取符号并根据其类型(操作数或运算符)进行相应处理来实现计算。对于操作数,将其压入栈中;对于运算符,则从栈中弹出两个元素进行计算并将结果压回栈中。

Stack    Aizu - ALDS1_3_A

Write a program which reads an expression in the Reverse Polish notation and prints the computational result.

An expression in the Reverse Polish notation is calculated using a stack. To evaluate the expression, the program should read symbols in order. If the symbol is an operand, the corresponding value should be pushed into the stack. On the other hand, if the symbols is an operator, the program should pop two elements from the stack, perform the corresponding operations, then push the result in to the stack. The program should repeat this operations.

Input

An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.

You can assume that +, - and * are given as the operator and an operand is a positive integer less than 106

Output

Print the computational result in a line.

Constraints

2 ≤ the number of operands in the expression ≤ 100
1 ≤ the number of operators in the expression ≤ 99
-1 × 109 ≤ values in the stack ≤ 109

Sample Input 1

1 2 +

Sample Output 1

3

Sample Input 2

1 2 + 3 4 - *

Sample Output 2

-3

Notes

Template in C


本题就是一个裸的栈问题,计算后缀表答式,具体后追表达式是什么就不清楚的讲了,网上很多,只要知道从右往左一次遍历,遇到一个符号就取出他的前两个数来计算,因为还存在括号这种情况所以会使用到栈。而我的代码则是用数组模拟栈,老实说我觉得STL的栈真的很慢。

简单题不多说,直接上代码:

 1     #include <iostream>  
 2     #include <cstdio>  
 3     #include <cstdlib>  
 4     #include <cstring>  
 5     using namespace std;  
 6       
 7     const int maxn = 100 + 5;  
 8       
 9     int top = 0;  
10     int S[1000];  
11       
12     void push(int key){  
13       S[++top] = key;  
14       return;  
15     }  
16       
17     int pop(){  
18       top--;  
19       return S[top+1];  
20     }  
21       
22     int main(){  
23       int a,b;  
24       top = 0;  
25       char s[maxn];  
26       while(scanf("%s",s) != EOF){  
27         if(s[0] == '+'){  
28           a = pop();  
29           b = pop();  
30           push(a+b);  
31         }  
32         else if(s[0] == '-'){  
33           b = pop();  
34           a = pop();  
35           push(a-b);  
36         }  
37         else if(s[0] == '*'){  
38           a = pop();  
39           b = pop();  
40           push(a*b);  
41         }  
42         else{  
43           push(atoi(s));  
44         }  
45       }  
46       printf("%d\n",pop());  
47     }  

 

转载于:https://www.cnblogs.com/fengsz/p/6207044.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值