150. Evaluate Reverse Polish Notation

来源:互联网 发布:蝎子网络第一季百度云 编辑:程序博客网 时间:2024/05/22 08:24

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
题意:逆波兰式的运算结果。

思路:用栈实现。仿佛回到了,大二刚开学时的数据结构实验。简易版计算器的编写。

class Solution {public:int evalRPN(vector<string>& tokens) {stack<int> mystack;for (int i = 0; i < tokens.size(); i++){string s = tokens[i];if (s.compare("+") == 0){int a = mystack.top();mystack.pop();int b = mystack.top();mystack.pop();mystack.push(a + b);continue;}if (s.compare("-") == 0){int a = mystack.top();mystack.pop();int b = mystack.top();mystack.pop();mystack.push(b - a);continue;}if (s.compare("*") == 0){int a = mystack.top();mystack.pop();int b = mystack.top();mystack.pop();mystack.push(a * b);continue;}if (s.compare("/") == 0){int a = mystack.top();mystack.pop();int b = mystack.top();mystack.pop();mystack.push(b / a);continue;}mystack.push(atoi(s.c_str()));}return mystack.top();}};










0 0
原创粉丝点击