栈_CodeUp_1918

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

 

posted @ 2019-03-02 10:36  pha创噬  阅读(159)  评论(0编辑  收藏  举报