逆波特兰式

483 阅读1分钟

计算逆波兰式(后缀表达式)的值,运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式。

题目链接

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        stack<int>store;
        int n,p,t;
        for(auto c: tokens){
            if(c=="+"||c=="-"||c=="*"||c=="/")
            {
                if(store.size()<2)return 0;
                n=store.top();store.pop();
                p = store.top();store.pop();
                if(c=="+")
                    t=p+n;
                else if(c=="-")
                    t=p-n;
                else if(c=="/")
                    t=p/n;
                else if(c=="*")
                    t=p*n;
                store.push(t);
            }
            else
            {
                store.push(stoi(c));
            }
        }
        return store.top();
    }
};