逆波兰表达式求值

逆波兰表达式求值

150. 逆波兰表达式求值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
int n=tokens.size();
for(int i=0;i<n;i++){
if(tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/"){
int num2 = stk.top();
stk.pop();
int num1 = stk.top();
stk.pop();
if(tokens[i]=="+"){
stk.push(num1+num2);
}
if(tokens[i]=="-"){
stk.push(num1-num2);
}
if(tokens[i]=="*"){
stk.push(num1*num2);
}
if(tokens[i]=="/"){
stk.push(num1/num2);
}
}else{ //数字入栈
stk.push(stoi(tokens[i]));
}
}
return stk.top();
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func evalRPN(tokens []string) int {
stk := []int{} // 用切片模拟栈
n := len(tokens)
for i := 0; i < n; i++ {
if tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/" {
num2 := stk[len(stk)-1]
stk = stk[:len(stk)-1]
num1 := stk[len(stk)-1]
stk = stk[:len(stk)-1]
if tokens[i] == "+" {
stk = append(stk, num1+num2)
}
if tokens[i] == "-" {
stk = append(stk, num1-num2)
}
if tokens[i] == "*" {
stk = append(stk, num1*num2)
}
if tokens[i] == "/" {
stk = append(stk, num1/num2)
}
} else { // 数字入栈
num, _ := strconv.Atoi(tokens[i])
stk = append(stk, num)
}
}
return stk[len(stk)-1]
}
-------------本文结束 感谢阅读-------------
0%