表达式求值(堆栈经典应用)

本文探讨了堆栈在计算数学表达式时的重要作用。通过中缀表达式到后缀表达式的转换,利用堆栈进行运算符管理和求值,详细阐述了堆栈的经典应用场景。了解这一过程对于理解计算机科学中的数据结构和算法至关重要。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <cstring>
#include <cstdio>
#include<queue>
#include<string>
#include<stack>
using namespace std;
int pri[5][5] = {
    1,0,0,0,0,
    1,0,0,0,0,
    1,0,0,0,0,
    1,1,1,0,0,
    1,1,1,0,0
};
char str[220];
stack<int>op;
stack<double>in;

void getOp(bool &reto,int &retn,int &i){
    if(i == 0 && op.empty()){
        reto = true;
        retn = 0;
        return;
    }
    if(str[i] == 0){
        reto = true;
        retn = 0;
        return;
    }
    if(str[i] >= '0' && str[i] <= '9'){
        reto = false;
        retn = 0;
    }
    else{
        reto = true;
        if(str[i] == '+') retn = 1;
        else if (str[i] == '-')  retn = 2;
        else if (str[i] == '*')  retn = 3;
        else if (str[i] == '/')  retn = 4;
        i += 2;
        return;
    }
    for(;str[i] != ' ' && str[i] != 0;++i){
        retn *= 10;
        retn += str[i] - '0';
    }
    if(str[i] == ' ')++i;
    return;
}


int main(){
    while(gets(str) ){
            if(str[0] == '0' && str[1] == 0)break;
        int retn;bool reto; int idx = 0;
        while(!op.empty())op.pop();
        while(!in.empty())in.pop();
        while(1){
            getOp(reto,retn,idx);
            if(!reto){
                in.push((double)retn);
            }
            else{
                if(op.empty() || pri[retn][op.top()] == 1)op.push(retn);
                else{
                    while(pri[retn][op.top()] == 0){
                        int tmp = op.top();
                        op.pop();
                        double b = in.top();
                        in.pop();
                        double a = in.top();
                        in.pop();
                        if(tmp == 1)in.push(a+b);
                        if(tmp == 2)in.push(a-b);
                        if(tmp == 3)in.push(a*b);
                        if(tmp == 4)in.push(a/b);

                    }
                    op.push(retn);
                }
            }
            if(op.size() == 2 && op.top()== 0){
                break;
            }
        }

                printf("%.2f\n",in.top());
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值