首页 > 其他 > 详细

栈_CodeUp_1918

时间:2019-03-02 10:50:12      阅读:248      评论:0      收藏:0      [点我收藏+]

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

 

栈_CodeUp_1918

原文:https://www.cnblogs.com/phaLQ/p/10460031.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!