中缀

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
char sta1[N]; 
int sta2[N]; 
int t1,t2;
string s;
bool isdigit(char a){
    if(a >= '0' && a <= '9') return true;
    return false;
}
void eval(){
    int b=sta2[t2]; t2--;
    int a=sta2[t2]; t2--;
    char op=sta1[t1]; t1--;
    t2++;
    if(op == '+')sta2[t2] = a + b;
    else if(op == '-')sta2[t2] = a - b;
    else if(op == '*')sta2[t2] = a*b;
    else if(op == '/')sta2[t2] = a/b;
}
int main(){
    cin >> s;
    int n = s.size();
    map<char,int>mp { { '+' , 1 } , { '-' , 1 } , { '*' , 2 } , { '/' , 2 } } ;
    for(int i = 0;i < n;i++){
        if(isdigit(s[i])){
            int t = 0;
            int j = i;
            while(isdigit(s[j])){
                t = t*10+(s[j]-'0');
                j++;
            }
            i = j-1;
            sta2[++t2] = t;
        }
        else {
            if(s[i] == '(')sta1[++t1] = s[i];
            else if(s[i] == ')'){
                while(t1 && sta1[t1] != '(') eval();
                t1--;
            }
            else{
                while(t1 && sta1[t1] != '(' && mp[sta1[t1]] >= mp[s[i]]) eval();
                sta1[++t1]=s[i];
            }
        }
    }
    while(t1) eval();
    cout << sta2[t2] << endl;
    return 0;
}

后缀

#include<bits/stdc++.h>
using namespace std;
stack<int> s;
int main(){
    while(true){
        char c = getchar();
        if(c == '\n')break;
        if('0'<=c && c<='9'){
            int x = 0;
            while('0'<=c && c<='9'){
                x *= 10;
                x += c-'0';
                c = getchar();
            }
            s.push(x);
        }
        else{
            int b = s.top(); s.pop();
            int a = s.top(); s.pop();
                 if(c=='+') s.push(a+b);
            else if(c=='-') s.push(a-b);
            else if(c=='*') s.push(a*b);
            else if(c=='/') s.push(a/b);
        }
    }
    cout << s.top();
    return 0;
}