150. 逆波兰表达式求值

  1. class Solution {
  2. public int evalRPN(String[] tokens) {
  3. Deque<Integer> stack = new LinkedList<>();
  4. for (String token : tokens) {
  5. if (token.equals("+")) {
  6. stack.push(stack.pop() + stack.pop());
  7. } else if (token.equals("-")) {
  8. int num1 = stack.pop();
  9. int num2 = stack.pop();
  10. stack.push(num2 - num1);
  11. } else if (token.equals("*")) {
  12. stack.push(stack.pop() * stack.pop());
  13. } else if (token.equals("/")) {
  14. int num1 = stack.pop();
  15. int num2 = stack.pop();
  16. stack.push(num2 / num1);
  17. } else {
  18. stack.push(Integer.parseInt(token));
  19. }
  20. }
  21. return stack.peek();
  22. }
  23. }