栈_CodeUp_1918

本文介绍了一个使用栈和队列的数据结构来解析并计算数学表达式的算法。通过将输入字符串转换为后缀表达式,然后计算得到结果。文章详细展示了如何处理操作数和运算符,以及如何正确地应用运算符优先级。

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

ac代码:

#include <iostream>
#include <cstdio>
#include <string>
#include <map>
#include <stack>
#include <queue>
using namespace std;


struct node{
    double digit;
    char op;
    bool sign;     //true:number , false:c
};


string str;
stack<node> s;     //op
queue<node> q;     //后缀 
map<char, int> mp;


void Seperate(void){
    double number=0;
    node tmp;
    for(int i = 0; i < str.length();){
        if(str[i]>='0' && str[i]<='9'){
            tmp.sign = true;
            tmp.digit = str[i++] - '0';
            while(i<str.length() && str[i]>='0' && str[i]<='9'){
                tmp.digit = tmp.digit *10 + (str[i] - '0');
                i++;
            }
            q.push(tmp);
        }
        else{
            while(!s.empty() && mp[str[i]]<=mp[s.top().op]){
                q.push(s.top());
                s.pop();
            }
            tmp.op = str[i];
            tmp.sign = false;
            s.push(tmp);
            i++;
        }
    }
    
    while(!s.empty()){     //将剩下的操作符全部放进后缀表达式中 
        q.push(s.top());
        s.pop();
    }
}

double caculate(void){
    node tmp,cur;
    double count1,count2,count;
    while(!q.empty()){
        cur = q.front();
        q.pop();
        if(cur.sign == true){
            s.push(cur);
        }
        else{
            count2 = s.top().digit;
            s.pop();
            count1 = s.top().digit;
            s.pop();
            if(cur.op == '-')    count = count1 - count2;
            else if(cur.op == '+')    count = count1 + count2;
            else if(cur.op == '*')    count = count1 * count2;
            else    count = count1 / count2;
            tmp.digit = count;
            tmp.sign = true;
            s.push(tmp);
        }
    }
    
    return s.top().digit;
}


int main(void)
{
    freopen("in.txt","r",stdin);
    
    mp['-'] = mp['+'] = 1;
    mp['*'] = mp['/'] = 2;
    
    while(getline(cin,str) && str != "0"){
        for(string::iterator it = str.begin(); it < str.end(); it++){
            if(*it == ' '){
                str.erase(it);
            }
        }
        
        while(!s.empty())    s.pop();     //初始化 
        Seperate();
        printf("%.2lf\n",caculate());
    }
    
    
    fclose(stdin);
    return 0;
}

 

转载于:https://www.cnblogs.com/phaLQ/p/10460031.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值