-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpn.cpp
65 lines (64 loc) · 1.48 KB
/
rpn.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
#include <iostream>
#include <stack>
#include <sstream>
#include<string>
using namespace std;
bool isOperator(const string & token) {
return token == "+" || token == "-" || token == "*" || token == "/" || token == "min" || token == "max";
}
bool isDigit(const string & token) {
return token <= "9" && token >= "0";
}
int getPriority(const string & token) {
if (token == "+" || token == "-") return 1;
if (token == "*" || token == "/") return 2;
if (token == "min" || token == "max") return 3;
return 0;
}
string rpn(string input) {
string postfix = "";
string output = "", token;
stack < string > s;
istringstream iss(input);
while (iss >> token) {
if (isDigit(token)) {
postfix += token;
postfix += " ";
} else if (isOperator(token)) {
while (!s.empty() && getPriority(s.top()) >= getPriority(token)) {
postfix += s.top();
postfix += " ";
s.pop();
}
s.push(token);
} else if (token == "(") {
s.push(token);
} else if (token == ")") {
while (!s.empty() && s.top() != "(") {
postfix += s.top();
postfix += " ";
s.pop();
}
s.pop();
} else if (token == ",") {
while (s.top() != "(") {
postfix += s.top();
postfix += " ";
s.pop();
}
}
}
while (!s.empty()) {
postfix += s.top();
postfix += " ";
s.pop();
}
return postfix;
}
int main() {
string s;
getline(cin, s);
string ans = rpn(s);
cout << ans;
return 0;
}