将中缀式转化为逆波兰式 (栈)

逆波兰式:Reverse Polish notation,RPN,,也叫后缀表达式,将运算符写在操作数之后

数据结构:两个栈S1和S2。S1临时存储运算符,S2存储最终结果。

算法:
(1)若取出的字符是操作数,则分析出完整的运算数,该操作数直接送入S2栈
(2)若取出的字符是运算符,则将该运算符与S1栈栈顶元素比较,如果该运算符优先级大于S1栈栈顶运算符优先级,则将该运算符进S1栈,否则,将S1栈的栈顶运算符弹出,送入S2栈中,直至S1栈栈顶运算符低于(不包括等于)该运算符优先级,则将该运算符送入S1栈。
(3)若取出的字符是“(”,则直接送入S1栈栈顶。
(4)若取出的字符是“)”,则将距离S1栈栈顶最近的“(”之间的运算符,逐个出栈,依次送入S2栈,此时抛弃“(”。
(5)重复上面的1~4步,直至处理完所有的输入字符
(6)最后将S1栈内所有运算符,逐个出栈,依次送入S2栈。

class Solution {
public:
    string ReversePolishNotation(string exp) { //假设操作数都是单个数字
        map< char, int > opPriority;
        opPriority['+'] = 1;
        opPriority['-'] = 1;
        opPriority['*'] = 2;
        opPriority['/'] = 2;
        opPriority['('] = 0;
        stack rpnStack;
        stack tmpStack;
        for(int i = 0; i < exp.size(); i++){
            if(exp[i] <= '9' && exp[i] >= '0') rpnStack.push(exp[i]);
            else if(exp[i]==')'){
                while(tmpStack.top()!='('){
                    rpnStack.push(tmpStack.top());
                    tmpStack.pop();
                }
                tmpStack.pop();
            }
            else if(exp[i]=='(' || tmpStack.empty()) tmpStack.push(exp[i]);
            else{
                while(!tmpStack.empty() && opPriority[tmpStack.top()] > opPriority[exp[i]]) {
                    rpnStack.push(tmpStack.top());
                    tmpStack.pop();
                }
                tmpStack.push(exp[i]);
            }
        }
        while(!tmpStack.empty() ){
            rpnStack.push(tmpStack.top());
            tmpStack.pop();
        }
        string ret = "";
        while(!rpnStack.empty() ){
            ret = rpnStack.top() + ret;
            rpnStack.pop();
        }
        return ret;
    }
};

 

posted on 2015-10-01 11:10  joannae  阅读(897)  评论(0编辑  收藏  举报

导航