中缀表达式转后缀表达式 (栈)

【题目链接】

    http://ybt.ssoier.cn:8088/problem_show.php?pid=1356

【代码】

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int dict[128];
 4 int i,tot,a,b;
 5 char s[110],ss[110];
 6 stack<char> rec;
 7 stack<int> tmp;
 8 int main()
 9 {
10     dict['+']=dict['-']=1;
11     dict['*']=dict['/']=2;
12     dict['^']=3;
13     scanf("%s",s+1);
14     for(i=1;s[i]!='\0';i++) {
15         if(isdigit(s[i])) { while(isdigit(s[i])) ss[++tot]=s[i++]; i--; ss[++tot]=' '; }
16         else switch(s[i]) {
17             case '(': rec.push('('); break;
18             case ')': while(rec.top()!='(') ss[++tot]=rec.top(), rec.pop(); rec.pop(); break;
19             default:
20                 while(rec.size()&&dict[rec.top()]>=dict[s[i]]) ss[++tot]=rec.top(), rec.pop(); rec.push(s[i]);
21         }
22 
23     }
24     while(rec.size()) ss[++tot]=rec.top(),rec.pop();
25     for(i=1;i<=tot;i++)
26         if(isdigit(ss[i])) {
27             int cur=0;
28             while(isdigit(ss[i])) cur=cur*10+ss[i++]-'0';
29             tmp.push(cur);
30         }
31         else{
32             int k=1;
33             a=tmp.top();tmp.pop();
34             b=tmp.top();tmp.pop();
35             switch(ss[i]) {
36                 case '+': tmp.push(a+b); break;
37                 case '-': tmp.push(b-a); break;
38                 case '*': tmp.push(a*b); break;
39                 case '/': tmp.push(b/a); break;
40                 case '^': for(int j=1;j<=a;j++) k*=b; tmp.push(k); break;
41             }
42         }
43     printf("%d\n",tmp.top());
44     return 0;
45 }

 

转载于:https://www.cnblogs.com/Willendless/p/9403837.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值