题目
https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
代码
遇到运算符号,就把栈顶两个元素拿出来运算,算完结果入栈。
遇到数字,直接入栈。
class Solution {
public int evalRPN(String[] tokens) {
int len=tokens.length;
Deque<Integer> stack=new LinkedList<>();
for(int i=0;i<len;i++){
if(tokens[i].equals("*")){
int a=stack.pop();
int b=stack.pop();
stack.push(b*a);
}
else if(tokens[i].equals("/")){
int a=stack.pop();
int b=stack.pop();
stack.push(b/a);
}
else if(tokens[i].equals("+")){
int a=stack.pop();
int b=stack.pop();
stack.push(b+a);
}
else if(tokens[i].equals("-")){
int a=stack.pop();
int b=stack.pop();
stack.push(b-a);
}
else{
int num=Integer.parseInt(tokens[i]);
stack.push(num);
}
}
return stack.pop();
}
}