-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevalReversePorlandExpression.h
62 lines (56 loc) · 1.33 KB
/
evalReversePorlandExpression.h
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
//
// Created by yindong on 19-6-3.
//
#ifndef SRC_EVALREVERSEPORLANDEXPRESSION_H
#define SRC_EVALREVERSEPORLANDEXPRESSION_H
#include<vector>
#include<string>
#include<iostream>
#include<stack>
using namespace std;
class EvalRPN {
public:
stack<int> s;
int evaluate(string op, int a, int b) {
int res = 0;
if(op == "+"){
res = a + b;
}
else if(op == "-"){
res = a - b;
}
else if(op == "*"){
res = a * b;
}
else if(op == "/") {
res = a / b;
}
else{
cout << "Error!!!" << endl;
}
return res;
}
bool isOperator(string s){
if(s == "+" or s == "-" or s == "*" or s == "/")
return true;
else
return false;
}
int evalRPN(vector<string>& tokens) {
int a, b, res;
for(auto ptr = tokens.begin(); ptr != tokens.end(); ptr++){
if(isOperator(*ptr)){
b = s.top(); s.pop();
a = s.top(); s.pop();
res = evaluate(*ptr, a, b);
s.push(res);
}
else{
s.push(stoi(*ptr));
}
}
cout << "size of stack: " << s.size() << endl;
return s.top();
}
};
#endif //SRC_EVALREVERSEPORLANDEXPRESSION_H