栈的应用---表达式求值(C++)

该文介绍了一种使用C++编程实现中缀表达式到后缀表达式的转换,并通过操作数栈和运算符栈来求解表达式的方法。主要涉及了优先级判断、括号处理和运算符处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

栈的应用—表达式求值(C++)

中缀表达式和后缀表达式

操作数栈和运算符栈

代码main.cpp
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int priority(const char ch)
{
    switch (ch)
    {
    case '+':
    case '-':
        return 1;
    case '*':
    case '/': 
        return 2;
    default:
        return 0;
    }
}

/**
 * \brief calculate an expression
 * \param a left operand
 * \param b right operand
 * \param ch operator
 * \return result
 */
int calculate(const int a,const int b,const char ch)
{
    switch (ch)
    {
    case '+':
        return a + b;
    case '-':
        return a - b;
    case '*':
        return a * b;
    case '/':
        return a / b;
    default:
        return 0;    //never happen
    }
}

/**
 * \brief judge whether a char is an operator or not
 * \param ch operator
 * \return is operator or not
 */
bool is_operator(const char ch)
{
    return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}

int evaluate(string expression)
{
    stack<int> operand;    //operand stack
    stack<char> optr;    //operator stack

    for (int i = 0; i < expression.length(); ++i)
    {
        char currentCh = expression[i];
        if (currentCh == ' ')  // neglect white space
        {
            continue;
        }
        else if (isdigit(currentCh))    //push operand stack
        {
            int num = expression[i] - '0';

            while(i + 1 < expression.length() && isdigit(expression[i+1]))
            {
                num *= 10;
                num += (expression[++i] - '0');
            }

            // cout << num;
            operand.push(num);
        }
        else if (currentCh == '(')    // push '(' to stack
        {
            optr.push('(');
        }
        else if (currentCh == ')')    // calculate expression in bracket
        {
            char cal = optr.top();
            optr.pop();

            while (!optr.empty() && cal != '(')
            {
                int a = operand.top();
                operand.pop();
                int b = operand.top();
                operand.pop();

                operand.push(calculate(b, a, cal));

                cal = optr.top();
                optr.pop();
            }
        }
        else if (is_operator(currentCh))
        {
            // if currentChar's priority is bigger than top's, push it to stack
            if (optr.empty() || priority(currentCh) > priority(optr.top()))
            {
                optr.push(currentCh);
            }
            else
            {
                char cal = optr.top();
                optr.pop();
                optr.push(currentCh);

                int a = operand.top();
                operand.pop();
                int b = operand.top();
                operand.pop();

                operand.push(calculate(b, a, cal));
            }
        }
    }

    while ( operand.size() > 1)
    {
        char cal = optr.top();
        optr.pop();

        int a = operand.top();
        operand.pop();
        int b = operand.top();
        operand.pop();

        operand.push(calculate(b, a, cal));
    }

    return operand.top();
}

int main()
{
    cout << evaluate("6 / 3") << endl;
    cout << evaluate("(6 / 3)") << endl;
    cout << evaluate("2 + 2 * 3") << endl;
    cout << evaluate("14+((13-2)*2-11*5)*2") << endl;


    return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值