zoukankan      html  css  js  c++  java
  • 【模板】中缀表达式求值

    #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();
        }
    }
  • 相关阅读:
    muduo库源码剖析(一) reactor模式
    POSIX 线程编程(二)线程建立与终止
    visual assist常用快捷键
    Linux下 静态链接库 和 动态链接库
    linux(Ubuntu)下mysql字符集完美解决
    共享内存解读
    hdu2829
    hdu3525
    2013ACM-ICPC亚洲区南京站现场赛G题
    poj1487
  • 原文地址:https://www.cnblogs.com/greenty1208/p/9612630.html
Copyright © 2011-2022 走看看