表达式的计算

  • 分两步:(1)中缀转后缀;(2)计算后缀表达式
  • (1)中缀转后缀
    • 操作数的顺序不变;
    • 从左到右扫描,遇到操作数直接输出,遇到操作符,如果栈顶操作符的栈内优先级高于等于当前扫描操作符的入栈优先级,则该操作符出栈,负责扫描操作符入栈;
    • 左括号特殊处理:入栈优先级最高,出栈优先级最低,除了右括号。
#include<iostream>
#include<map>
#include<stack>
#include<string>

using namespace std;

string postFix(const string str) {
    map<char,int> isp;
    map<char,int> icp; // isp栈内优先级,icp入栈优先级
    isp.insert(pair<char, int> ('*',1)); isp.insert(pair<char, int> ('/',1)); isp.insert(pair<char, int> ('%',1));
    isp.insert(pair<char, int> ('+',2)); isp.insert(pair<char, int> ('-',2));
    isp.insert(pair<char, int> ('(',3));isp.insert(pair<char, int> (')',4));
    isp.insert(pair<char, int> ('#',10));

    icp.insert(pair<char, int> ('(',0));
    icp.insert(pair<char, int> ('*',1)); icp.insert(pair<char, int> ('/',1)); icp.insert(pair<char, int> ('%',1));
    icp.insert(pair<char, int> ('+',2)); icp.insert(pair<char, int> ('-',2)); icp.insert(pair<char, int> (')',4));

    string pStr;
    stack<char> sta;
    sta.push('#');

    for (auto c : str) {
        if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')) {
            pStr.append(1, c);
        } else {
            if (c == ')') {
                char y = sta.top(); sta.pop();
                while (y != '(') {
                    pStr.append(1, y);
                    y = sta.top(); sta.pop();
                }
            } else {
                char y = sta.top(); sta.pop();
                while (isp[y] <= icp[c]) {
                    pStr.append(1, y);
                    y = sta.top(); sta.pop();
                }
                sta.push(y);
                sta.push(c);
            }
        }
    }
    while (!sta.empty()) {
        char y = sta.top();
        sta.pop();
        if (y != '#') {
            pStr.append(1, y);
        }
    }
    return pStr;
}

int main() {
    string str, pStr;
    cin>>str;
    pStr = postFix(str);
    cout<<pStr<<endl;
    return 0;
}
  • (2)后缀表达式的计算
    • 从左到右扫描,将操作数入栈;
    • 遇到操作符,从栈中取出两个操作数,计算,结果入栈。

 

posted on 2017-09-10 22:27  Valenpqq  阅读(175)  评论(0)    收藏  举报