s.empty(); //如果栈为空则返回true, 否则返回false;
s.size(); //返回栈中元素的个数
s.top(); //返回栈顶元素, 但不删除该元素
s.pop(); //弹出栈顶元素, 但不返回其值
s.push(); //将元素压入栈顶
题目描述
计算逆波兰式(后缀表达式)的值
运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式
例如:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9↵ ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
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) {
int len = tokens.size();
stack<int> s;
for(int i = 0; i < len ; ++i)
{
if((tokens[i] == "+") || (tokens[i] == "-") || (tokens[i] == "*") || (tokens[i] == "/"))
{
int b = s.top();
s.pop();
int a = s.top();
s.pop();
int temp = ope(a, b, tokens[i]);
s.push(temp);
}
else
{
s.push(stoi(tokens[i]));
}
}
return s.top();
}
int ope(int a, int b, string s)
{
if(s == "+") return a + b;
else if (s == "-") return a - b;
else if (s == "*") return a * b;
else return a / b;
}
};