利用栈实现逆波兰表达式
题目链接:
https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/
我们用栈来实现,遇到数字入栈,遇到运算符出栈,用stoi实现字符转整型。
int evalRPN(vector<string>& tokens) {stack<int>nums;auto it = tokens.begin();while (it != tokens.end()){if (*it == "+"){int tmp = nums.top();nums.pop();int tmp1 = nums.top();nums.pop();nums.push(tmp + tmp1);}else if (*it == "-"){int tmp = nums.top();nums.pop();int tmp1 = nums.top();nums.pop();nums.push(tmp1 - tmp);}else if (*it == "*"){int tmp = nums.top();nums.pop();int tmp1 = nums.top();nums.pop();nums.push(tmp1 * tmp);}else if (*it == "/"){int tmp = nums.top();nums.pop();int tmp1 = nums.top();nums.pop();nums.push(tmp1 / tmp);}else {nums.push(stoi(*it));}it++;}return nums.top();