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));
}


  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值