-
Notifications
You must be signed in to change notification settings - Fork 1
/
RPN.h
99 lines (97 loc) · 1.64 KB
/
RPN.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <cctype>
#include <cstdlib>
#include <stack>
#include <sstream>
using namespace std;
void convert2RPN(string &s) {
stringstream ss;
stack<char> stk;
for (size_t i = 0; i < s.length(); i++) {
if (isdigit(s.at(i))) {
ss << s.at(i);
if ((i < s.length() - 1 && !isdigit(s.at(i + 1)))
|| i == s.length() - 1) {
ss << ' ';
}
}
else {
if (stk.empty()) {
stk.push(s.at(i));
}
else {
switch (s.at(i)) {
case '(':
stk.push(s.at(i));
break;
case ')':
while (stk.top() != '(') {
ss << stk.top();
stk.pop();
}
stk.pop();
break;
case '+':
case '-':
while (!stk.empty() && stk.top() != '(') {
ss << stk.top();
stk.pop();
}
stk.push(s.at(i));
break;
case '*':
case '/':
while (!stk.empty() && (stk.top() == '*' || stk.top() == '/')) {
ss << stk.top();
stk.pop();
}
stk.push(s.at(i));
break;
}
}
}
}
while (!stk.empty()) {
ss << stk.top();
stk.pop();
}
s = ss.str();
}
float calculateRPN(const string &s) {
stack<float> stk;
for (size_t i = 0; i < s.length(); i++) {
if (isdigit(s.at(i))) {
int e = atoi(&s.at(i));
int t = e / 10;
while (t > 0) {
i++;
t /= 10;
}
i++;
stk.push(e);
}
else {
float r = stk.top();
stk.pop();
float l = stk.top();
stk.pop();
float result;
switch (s.at(i)) {
case '+':
result = l + r;
break;
case '-':
result = l - r;
break;
case '*':
result = l * r;
break;
case '/':
result = l / r;
break;
}
stk.push(result);
}
}
return stk.top();
}