【模板】中缀表达式求值

#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();
    }
}

 

全部评论

相关推荐

点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
05-01 13:13
ecece:这么明目张胆虚报就业率啊
点赞 评论 收藏
分享
头像
05-16 12:47
已编辑
中国地质大学(武汉) Java
你出生在农村,与其它农村小孩子无异小学时你对成绩没有概念,只感觉上课不听课也是无聊,只知道不写完作业会被老师罚站一到考试,自己成绩总是名列靠前,即使偶尔落后,你也从不在意中学时你觉得课本的东西很简单,随便学学就会了,并没有大量刷题你总是想不通,那些所谓的数学物理中难题,明明是在送分,为什么你的同学总是想不出解题方法高中时这三年你过的不容易,晚睡早起,给了自己很多压力.但是你也发现自己是有些小聪明的,你感觉班里有些同学很刻苦,但成绩比你差远了。那些数学题和物理题的陷阱,同学一遍遍踩坑,但是你总能发现并避开它们.“为了父母的期盼,为了恩师的厚望,为了天赐的智慧,为了青春的理想......”“天行健...
创作助手_刘北:其实,这种已经是神童级别的了,不费吹灰之力就能拿到自己想要的东西,就像机器按照程序走了一遍,就像我小时候看爱情公寓,觉得他们都很惨,几个人只能挤在一个房间里合租,但是好在他们有一群非常好的朋友,随着时间的推移,慢慢长大了,在看爱情公寓的时候,觉得他们都很厉害,博士、留学生、***、电台公子,数学天才,任何一个都是我可望而不可即的,更别说可以在异地认识一群更好的朋友了,所以呢,人还是要自给自足,满足当下,不要攀比,意气风发的且有理想的18岁少年永远都存在,只不过随着时间的推移他被你包裹在了洋葱的最深处。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务