逆波兰表达式求值 // java官方文档推荐用双端队列Deque实现栈,而非Stack,Deque较之Stack强大很多,Stack只能先进后出 // switch判断String时会用equals方法,而非== class Solution{ public int evalRPN(String[] tokens) { Deque<Integer> stack = new LinkedList<>(); for(int i = 0; i < tokens.length; i++){ if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/")){ int num2 = stack.pop(); int num1 = stack.pop(); switch(tokens[i]){ case "+": stack.push(num1 + num2); break; case "-": stack.push(num1 - num2); break; case "*": stack.push(num1 * num2); break; case "/": stack.push(num1 / num2); break; } }else{ stack.push(Integer.parseInt(tokens[i])); } } return stack.peek(); } }