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

一、后缀表达式求值

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

假定待求值的后缀表达式为: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。


代码:

#include<iostream>
#include<stack>
#include<stdio.h>
#include<string.h>
using namespace std;

int main(){
    string PostArray;
    int len,i,a,b;
    while(cin>>PostArray){
        stack<int> Stack;
        len = PostArray.length();
        for(i = 0;i < len;i++){
            //跳过空格
            if(PostArray[i] == ' '){
                continue;
            }
            //如果是数字则入栈
            if(PostArray[i] >= '0' && PostArray[i] <= '9'){
                Stack.push(PostArray[i] - '0');
            }
            //如果是字符则从栈读出两个数进行运算
            else{
                //算数a出栈
                a = Stack.top();
                Stack.pop();
                //算法b出栈
                b = Stack.top();
                Stack.pop();
                //进行运算(+ - * /)
                if(PostArray[i] == '+'){
                    Stack.push(a + b);
                }
                else if(PostArray[i] == '-'){
                    Stack.push(a - b);
                }
                else if(PostArray[i] == '*'){
                    Stack.push(a * b);
                }
                else if(PostArray[i] == '/'){
                    Stack.push(a / b);
                }
            }
        }//for
        printf("%d\n",Stack.top());
    }//while
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值