算法之中缀表达式和后缀表达式

一、后缀表达式求值

后缀表达式也叫逆波兰表达式,其求值过程可以用到栈来辅助存储。

假定待求值的后缀表达式为:6  5  2  3  + 8 * + 3  +  *,则其求值过程如下:


(1)遍历表达式,遇到的数字首先放入栈中,依次读入6 5 2 3 此时栈如下所示:


(2)接着读到“+”,则从栈中弹出3和2,执行3+2,计算结果等于5,并将5压入到栈中。


(3)然后读到8(数字入栈),将其直接放入栈中。


(4)读到“*”,弹出8和5,执行8*5,并将结果40压入栈中。

而后过程类似,读到“+”,将40和5弹出,将40+5的结果45压入栈...以此类推。最后求的值288。


代码:

[cpp]  view plain copy
  1. #include<iostream>  
  2. #include<stack>  
  3. #include<stdio.h>  
  4. #include<string.h>  
  5. using namespace std;  
  6.   
  7. int main(){  
  8.     string PostArray;  
  9.     int len,i,a,b;  
  10.     while(cin>>PostArray){  
  11.         stack<int> Stack;  
  12.         len = PostArray.length();  
  13.         for(i = 0;i < len;i++){  
  14.             //跳过空格  
  15.             if(PostArray[i] == ' '){  
  16.                 continue;  
  17.             }  
  18.             //如果是数字则入栈  
  19.             if(PostArray[i] >= '0' && PostArray[i] <= '9'){  
  20.                 Stack.push(PostArray[i] - '0');  
  21.             }  
  22.             //如果是字符则从栈读出两个数进行运算  
  23.             else{  
  24.                 //算数a出栈  
  25.                 a = Stack.top();  
  26.                 Stack.pop();  
  27.                 //算法b出栈  
  28.                 b = Stack.top();  
  29.                 Stack.pop();  
  30.                 //进行运算(+ - * /)  
  31.                 if(PostArray[i] == '+'){  
  32.                     Stack.push(a + b);  
  33.                 }  
  34.                 else if(PostArray[i] == '-'){  
  35.                     Stack.push(a - b);  
  36.                 }  
  37.                 else if(PostArray[i] == '*'){  
  38.                     Stack.push(a * b);  
  39.                 }  
  40.                 else if(PostArray[i] == '/'){  
  41.                     Stack.push(a / b);  
  42.                 }  
  43.             }  
  44.         }//for  
  45.         printf("%d\n",Stack.top());  
  46.     }//while  
  47.     return 0;  
  48. }  



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值