[C++]数据结构--栈--后缀表达式求值

本文介绍了一段C++代码,用于计算后缀表达式(逆波兰表示法),支持正整数输入和基本的加减乘除运算,通过栈实现表达式求值过程。代码配合B站上印度程序员的数据结构课程讲解进行解析。

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

// 后缀表达式求值    1.支持输入正整数,可输入多数位数字,如15,200等  2.表达式间隔使用空格或,  3.支持加减乘除四种运算
/*示例:
正常表达式:
3*2+15*2-9
后缀表达式:
3 2 * 15 2 * + 9 -
*/
#include <iostream>
#include <string>
#include <stack>

using namespace std;
// 判断当前字符是否为运算符
bool isoperator(char c)
{
    if (c == '+' || c == '-' || c == '*' || c == '/')
    {
        return true;
    }
    else
    {
        return false;
    }
}
// 判断当前字符是否为数字
bool isnum(char c)
{
    if (c >= '0' && c <= '9')
    {
        return true;
    }
    else
    {
        return false;
    }
}
// 获取运算符运算结果
double performoperator(char op, double num1, double num2)
{
    if (op == '+')
    {
        return num1 + num2;
    }
    else if (op == '-')
    {
        return num1 - num2;
    }
    else if (op == '*')
    {
        return num1 * num2;
    }
    else if (op == '/')
    {
        if (num2 != 0)
        {
            return num1 / num2;
        }
        else
        {
            cout << "除数不能为0" << endl;
            return -1;
        }
    }
    else
    {
        cout << "运算符错误" << endl;
        return -1;
    }
}
// 后缀表达式计算
// 考虑到存在除法,使用double类型
double postfix(string exp)
{
    int n = exp.length(); // 表达式长度
    stack<double> S;      // 用栈接收表达式中的数字,故栈的类型设为double
    for (int i = 0; i < n; i++)
    {
        if (exp[i] == ' ' || exp[i] == ',')
        {
            continue;
        }
        else if (isnum(exp[i]))
        {
            double operand = 0;//设置一个操作数,实现多数位数字接收
            while (i < exp.length() && isnum(exp[i]))
            {
                operand = (operand * 10) + (exp[i] - '0');
                i++;
            }
            i--;
            S.push(operand);
        }
        else if (isoperator(exp[i]))
        {
            // 一个小细节,这里num2是先出栈的,对于-和/运算符来说是减数/除数,需要放在performoperator参数列表中的num2位置
            double num2 = S.top();
            S.pop();
            double num1 = S.top();
            S.pop();
            double res = performoperator(exp[i], num1, num2);
            S.push(res);
        }
    }
    return S.top();
}

int main()
{
    string exp;
    cout << "请输入:";//参考用例3 2 * 15 2 * + 9 -
                      //正确结果:27
    getline(cin, exp);
    double res = 0;
    res = postfix(exp);
    cout << "= " << res << endl;
    cin.get();
    return 0;
}

参考:

B站搬运的一位印度程序员讲解的视频:数据结构:课程导论_哔哩哔哩_bilibili

视频配套代码地址(需要梯子可访问):https://gist.github.com/mycodeschool/7702441

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值