后缀表达式

【问题描述】
从键盘读入一个后缀表达式(字符串),只含有0-9组成的运算数及加(+)、减(—)、乘(*)、除(/)四种运算符。每个运算数之间用一个空格隔开,不需要判断给你的表达式是否合法。以@作为结束标志。

 

将数字存入栈中,遇到符号就计算栈顶和它下面的一个数并将得到的新得数存入栈。

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cmath>
 4 #include<cstring>
 5 #include<algorithm>
 6 #include<stack>
 7 using namespace std;
 8 const int maxn = 500;
 9 char a[maxn];
10 void solve(char a[])
11 {
12     stack<int>num;
13     int l = strlen(a), n = 0;
14     for(int i = 0; i < l; ++i)
15     {
16         if(a[i] >= '0' && a[i] <= '9')    //分离运算数 
17         {
18             n += a[i] - '0';    //n用来暂时储存所得的数 
19             if(a[i + 1] >= '0' && a[i + 1] <= '9') n *= 10;    
20             else {num.push(n); n = 0;}
21         }
22         if(a[i] == '+')
23         {
24             int x = num.top(); num.pop();
25             num.top() += x;
26         }
27         if(a[i] == '-')
28         {
29             int x = num.top(); num.pop();
30             num.top() -= x;
31         }
32         if(a[i] == '*')
33         {
34             int x = num.top(); num.pop();
35             num.top() *= x;
36         }
37         if(a[i] == '/')
38         {
39             int x = num.top(); num.pop();
40             num.top() /= x;
41         }
42     }
43     printf("%d\n", num.top());
44     return;
45 }
46 int main()
47 {
48     a[0] = getchar();
49     int i = 0;
50     while(a[i] != '@') a[++i] = getchar();
51     solve(a);
52     return 0;
53 }

 

 

posted @ 2018-01-21 15:28  mrclr  阅读(399)  评论(0编辑  收藏  举报