Leetcode Evaluate Reverse Polish Notation

来源:互联网 发布:linux ndk 编译的so 编辑:程序博客网 时间:2024/06/01 08:07

题意:后序运算。

思路:使用堆栈储存操作对象。

class Solution {public:    stack<int> ms;    int evalRPN(vector<string>& tokens) {        for(int i = 0; i < tokens.size(); ++ i) {            if(tokens[i][0] == '+' && tokens[i].length() == 1) {                int a = ms.top();                ms.pop();                int b = ms.top();                ms.pop();                ms.push(b + a);            }            else if (tokens[i][0] == '-' && tokens[i].length() == 1) {                int a = ms.top(); ms.pop();                int b = ms.top(); ms.pop();                ms.push(b - a);            }            else if (tokens[i][0] == '*' && tokens[i].length() == 1) {                int a = ms.top(); ms.pop();                int b = ms.top(); ms.pop();                ms.push(b * a);            }            else if (tokens[i][0] == '/' && tokens[i].length() == 1) {                int a = ms.top(); ms.pop();                int b = ms.top(); ms.pop();                ms.push(b / a);            }            else ms.push(std::stoi(tokens[i]));        }                return ms.top();    }};


0 0
原创粉丝点击