leetcode150_逆波兰表达式

1、题目

 

 2、分析

     用栈来解决问题

3、代码

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> result;
        int num1;
        int num2;
        for(int i=0; i<tokens.size(); i++){
            if (tokens[i]!="+" && tokens[i]!="-" && tokens[i]!="*" && tokens[i]!="/"){
                result.push(stoi(tokens[i]));
            }
            else{
                if(tokens.size()>=2 && tokens[i]=="+"){
                    num1 = result.top();
                    result.pop();
                    num2 = result.top();
                    result.pop();
                    result.push(num2+num1);
                }
                if(result.size()>=2 && tokens[i]=="-"){
                    num1 = result.top();
                    result.pop();
                    num2 = result.top();
                    result.pop();
                    result.push(num2-num1);
                }
                if(result.size()>=2 && tokens[i]=="*"){
                    num1 = result.top();
                    result.pop();
                    num2 = result.top();
                    result.pop();
                    result.push(num2*num1);
                }
                if(result.size()>=2 && tokens[i]=="/"){
                    num1 = result.top();
                    std::cout<<"num1 "<<num1<<std::endl;
                    result.pop();
                    num2 = result.top();
                    std::cout<<"num2 "<<num2<<std::endl;
                    result.pop();
                    int num = num2/num1;
                    std::cout<<"num "<<num2/num1<<std::endl;
                    result.push(num);
                }
            }
        }
        return result.top();
    }
};

 

posted @ 2021-12-16 10:02  星光夜  阅读(25)  评论(0编辑  收藏  举报