150. [栈]逆波兰表达式求值
150. 逆波兰表达式求值
将数字依次入栈,由于逆波兰表达式保证了栈内不会为空,所以我们可以将两数的操作结果重新入栈,最终栈内的数字即为运算结果。
// 执行用时: 6 ms , 在所有 Java 提交中击败了 89.98% 的用户
// 内存消耗: 38.7 MB , 在所有 Java 提交中击败了 40.45% 的用户
class Solution {
public int evalRPN(String[] tokens) {
LinkedList<Integer> stack = new LinkedList<>();
// int ans = 0;
for(String op : tokens){
if (op.equals("+")){
int top1 = stack.pollLast();
int top2 = stack.pollLast();
stack.offer(top2 + top1);
} else if (op.equals("-")){
int top1 = stack.pollLast();
int top2 = stack.pollLast();
… stack.offer(top2 * top1);
} else if (op.equals("*")){
int top1 = stack.pollLast();
int top2 = stack.pollLast();
… stack.offer(top2 * top1);
} else if (op.equals("/")){
int top1 = stack.pollLast();
int top2 = stack.pollLast();
… stack.offer(top2 / top1);
} else {
stack.offer(Integer.parseInt(op));
}
}
return stack.pollLast();
}
}

浙公网安备 33010602011771号