-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevalRPN.cpp
65 lines (60 loc) · 1.4 KB
/
evalRPN.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* Evaluate the value of an arithmetic expression in Reverse Polish Notation.
* Valid operators are +, -, *, /. Each operand may be an integer or another expression.
*
*
*/
/* stack
*
*
*/
#include <iostream>
#include <climits>
#include <algorithm>
#include <vector>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <queue>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
int evalRPN(std::vector<std::string> &tokens) {
std::stack<int> s;
for (const auto &t : tokens) {
if (t == "+") {
auto m = s.top(); s.pop();
auto n = s.top(); s.pop();
s.push(n + m);
} else if (t == "-") {
auto m = s.top(); s.pop();
auto n = s.top(); s.pop();
s.push(n - m);
} else if (t == "*") {
auto m = s.top(); s.pop();
auto n = s.top(); s.pop();
s.push(n * m);
} else if (t == "/") {
auto m = s.top(); s.pop();
auto n = s.top(); s.pop();
s.push(n / m);
} else {
int n = std::stoi(t);
s.push(n);
}
}
return s.top();
}
};
int main() {
Solution solute;
// std::vector<std::string> input{"2", "1", "+", "3", "*"};
std::vector<std::string> input{"4", "13", "5", "/", "+"};
auto res = solute.evalRPN(input);
std::cout << res << std::endl;
return 0;
}