天天看点

经典白话算法之中缀表达式和后缀表达式

一、后缀表达式求值

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

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

plaincopy

#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();  

                //进行运算(+ - * /)  

                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;  

}  

继续阅读