c++栈的应用 中缀表达式求值

//Geeksun 2018.04.01

#include <iostream>
#include <cstring>
#include <stack>
using namespace std;

int caculate(int a, int b, char sign);//计算函数
int level(char str);//计算运算级
void destack_two(stack<int>&s1, stack<char>& s2);//出栈s1中两个元素,s2中一个元素
int main()
{
    stack<int> s1;
    stack<char> s2;
    char str[100];
    cin >> str;
    int count = 0;
    int n = strlen(str);
    for (int i = 0; i <= n; i++)
    {
        if (str[i] == '#')
        {
            if (count == 0)
            {
                s2.push(str[i]);
                count++;
            }
            else
            {
                while (s1.size() != 1)
                {
                    destack_two(s1, s2);
                }
                cout << s1.top();
            }
        }
        else if (str[i] >= 48 && str[i] <= 57)
        {
            if (str[i - 1] >= 48 && str[i - 1] <= 57)
            {
                int temp = s1.top() * 10 + (str[i] - '0');
                s1.pop();
                s1.push(temp);
            }
            else
            {
                s1.push(str[i] - '0');
            }

        }
        else if (str[i] == '(')
        {
            s2.push(str[i]);
        }
        else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/')
        {
            if (level(str[i]) > level(s2.top()) || s2.top() == '(')
            {
                s2.push(str[i]);
            }
            else if (level(str[i]) <= level(s2.top()) && s2.top() != '(')
            {
                destack_two(s1,s2);
                s2.push(str[i]);
            }
        }
        else if (str[i] == ')')
        {
            while (s2.top() != '(')
            {
                destack_two(s1,s2);
            }
            s2.pop();
        }
    }
    return 0;
}
int caculate(int a, int b, char sign)
{
    switch (sign)
    {
    case '+':return a + b;
    case '-':return a - b;
    case '*':return a * b;
    case '/':return a / b;
    default:cout << "操作符不正确!\n";break;
    }
    return 0;
}
int level(char str)
{
    switch (str)
    {
        case'(': return 5;
        case')': return 5;
        case'*': return 4;
        case'/': return 4;
        case'+': return 1;
        case'-': return 1;
        case'#': return 0;
    }
    return 0;
}
void destack_two(stack<int>&s1, stack<char>& s2)
{
    int a, b;
    char sign;
    b = s1.top();
    s1.pop();
    a = s1.top();
    s1.pop();
    sign = s2.top();
    s2.pop();
    s1.push(caculate(a, b, sign));
}


猜你喜欢

转载自blog.csdn.net/geek_sun/article/details/79972230