150. Evaluate Reverse Polish Notation
Note: Be careful of the order of operands when doing subtraction or division.
class Solution {
public int evalRPN(String[] tokens) {
LinkedList<Integer> stack = new LinkedList<>();
int a, b;
for (String s : tokens) {
switch (s) {
case "+":
stack.addLast(stack.removeLast() + stack.removeLast());
break;
case "-":
a = stack.removeLast();
b = stack.removeLast();
stack.addLast(b - a);
break;
case "*":
stack.addLast(stack.removeLast() * stack.removeLast());
break;
case "/":
a = stack.removeLast();
b = stack.removeLast();
stack.addLast(b / a);
break;
default:
stack.addLast(Integer.parseInt(s));
break;
}
}
return stack.removeLast();
}
}