【模板】中缀表达式求值

#include <bits/stdc++.h>
using namespace std;

char s[105];
int n;
stack<char>st;
vector<char>vec;
void csh()
{
    vec.clear();
}
int comp(char x,char y) { // 定义运算符优先级: x 是否大于 y

void trans() 
{
    for(int i = 0;i<n;i++) 
    {
    if(isdigit(s[i-1]) && (!isdigit(s[i]))) vec.push_back('#');
    char t = s[i];
    if(t == '(') st.push(s[i]);
    else if(t == ')')
    {
        char op = st.top();
        while(op!='(') 
        {
        vec.push_back(op);
        st.pop();
        op = st.top();
        }
        st.pop();
    }
    else if(isdigit(t)) vec.push_back(t);
    else 
    {
        if(st.empty()) st.push(t);
        else
        {
        char stp = st.top();
        if(stp =='(' || comp(t,stp)) st.push(t);
        else 
        {
            while(!comp(t,stp) && !st.empty() && stp!='(') 
            {
            st.pop();
            vec.push_back(stp);
            if(!st.empty()) stp = st.top();
            }
            st.push(t);
        }
        }
    }
    } 
    vec.push_back('#');
    while(!st.empty()) 
    {
    char t = st.top();
    vec.push_back(st.top());
    st.pop();
    }
}


void cal() {
    stack< your_type >val; // 定义运算结果栈
    int pos = 0,now = 0;
    while(vec[pos]!='#') 
    {    
    now = now*10 + vec[pos]-'0';
    pos++;
    }
    val.push( your_type(now) );
    for(;pos<vec.size();pos++) 
    {
    char t = vec[pos];
    if(t == '#') continue;
    if(isdigit(t)) 
    {
        now = 0;
        while(pos < vec.size() && vec[pos]!='#') 
        {
        now = now*10 + vec[pos]-'0';
        pos++;
        }
        val.push(make_pair(now,now));
    }
    else
    {
        your_type y = val.top();val.pop();
        your_type x = val.top();val.pop();
        your_type tmp;

        /*
         * 对各种运算符进行运算 tmp = x op y
         */

        val.push(tmp);
    }
    }
    your_type ans = val.top();

}
int main()
{
    while(scanf("%s",s)!=EOF) 
    {
    csh();
    n = strlen(s);
    trans();
    cal();
    }
}

 

posted @ 2018-09-09 09:48  Greenty  阅读(799)  评论(0编辑  收藏  举报