LC150. 逆波兰表达式求值
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new LinkedList<Integer>();
for (int i = 0; i < tokens.length; ++i) {
String item = tokens[i];
if ("+".equals(item)) {
int num2 = stack.pop();
int num1 = stack.pop();
stack.push(num1 + num2);
}
else if ("-".equals(item)) {
int num2 = stack.pop();
int num1 = stack.pop();
stack.push(num1 - num2);
}
else if ("*".equals(item)) {
int num2 = stack.pop();
int num1 = stack.pop();
stack.push(num1 * num2);
}
else if ("/".equals(item)) {
int num2 = stack.pop();
int num1 = stack.pop();
stack.push(num1 / num2);
}
else {
stack.push(Integer.parseInt(item));
}
}
return stack.pop();
}
}
Post Views:
1