蓝桥杯ALGO-156 中缀表达式求值

题目链接:http://lx.lanqiao.cn/problem.page?gpid=T419

将中缀表达式通过栈转换为后缀表达式

#include<iostream>
#include<sstream>
#include<string>
#include<stack>
#include<vector>
using namespace std;

bool higher(char a, char b)
{
    if (b == '(' || b == ')')
        return 1;

    if (a == '*' || a == '/')
        if (b == '+' || b == '-')
            return 1;

    return 0;
}
void stack_vec(stack<char>&s, vector<string>&suffix)
{
    string str;
    str += s.top();
    suffix.push_back(str);
    s.pop();
}
int main()
{
    string nifix;
    stack<char>s;
    vector<string>suffix;

    cin >> nifix;
    for (int i = 0; i < nifix.size(); i++)
    {
        if (nifix[i] >= '0'&&nifix[i] <= '9')
        {
            string str;
            while (nifix[i] >= '0'&&nifix[i] <= '9')
            {
                str += nifix[i];
                i++;
            }
            i -= 1;
            suffix.push_back(str);
        }
        else if (nifix[i] == '+' || nifix[i] == '-' || nifix[i] == '*' || nifix[i] == '/')
        {
            if (s.empty())
                s.push(nifix[i]);
            else
            {
                if (higher(nifix[i], s.top()))
                    s.push(nifix[i]);
                else
                {
                    while (!s.empty() && !higher(nifix[i], s.top()))
                        stack_vec(s, suffix);
                    s.push(nifix[i]);
                }
            }
        }
        else if (nifix[i] == '(' || nifix[i] == ')')
        {
            if (nifix[i] == '(')
                s.push(nifix[i]);
            else
            {
                while (s.top() != '(')
                    stack_vec(s, suffix);
                s.pop();
            }
        }
    }
    while (!s.empty())
        stack_vec(s, suffix);

    stringstream ss;
    stack<int>ca;
    int x,x1,x2;

    for (int i = 0; i < suffix.size(); i++)
    {
        if (suffix[i] == "+" || suffix[i] == "-" || suffix[i] == "*" || suffix[i] == "/")
        {
            x2 = ca.top();
            ca.pop();
            x1 = ca.top();
            ca.pop();
            switch (suffix[i][0])
            {
                case '+':x = x1 + x2; break;
                case '-':x = x1 - x2; break;
                case '*':x = x1 * x2; break;
                case '/':x = x1 / x2; break;
                default:break;
            }
            ca.push(x);
        }
        else
        {
            ss << suffix[i];
            ss >> x;
            ca.push(x);
            ss.clear();
        }
    }
    cout << ca.top();
    //system("pause");
    return 0;
}

 

posted @ 2017-12-10 13:22  小九xD  阅读(283)  评论(0编辑  收藏  举报