给出一个逆波兰表达式,求该逆波兰表达式表达式的值。比如: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 解析:用栈来实现,遍历当前字符串,如果当前字符串可以转换为数组类型,则当前元素转换为数值,并且入栈,如果是运算符,则取出栈中两个元素。并计算当前两个元素的值。然后结果再次入栈。#include<iostream> #include<vector> #include<stack> #include<string> using namespace std; int getNum(int num1, int num2, string str) { int res = 0; if (str == "*") { res = num1 * num2; } else if (str == "/") { res = num1 / num2; } else if (str == "+") { res = num1 + num2; } else { res = num1 - num2; } return res; } int evalRPN(vector<string> &tokens) { stack<int> s; for (int i = 0; i < tokens.size(); ++i) { string str = tokens[i]; if (str == "+" || str == "-" || str == "*" || str == "/") { int num1 = s.top(); s.pop(); int num2 = s.top(); s.pop(); int res = getNum(num2, num1, str); s.push(res); } else { int num = stoi(tokens[i]); s.push(num); } } return s.top(); } int main(void) { vector<string> arr = { "4", "13", "5", "/", "+" }; cout << evalRPN(arr) << endl; system("pause"); return 0; }
逆波兰表达式求值
最新推荐文章于 2024-08-21 12:07:17 发布