-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfix_expression_with_brackets.cpp
77 lines (74 loc) · 1.81 KB
/
postfix_expression_with_brackets.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
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <stack>
#include <string>
using namespace std;
string in_to_post(string postfix);
bool isoperator(char c);
int priority(char c);
int main() {
int t;
cin >> t;
while (t--) {
string infix;
cin >> infix;
cout << in_to_post(infix) << endl;
}
return 0;
}
string in_to_post(string infix) {
string result;
stack<char> stk;
for (char c : infix) {
if (isoperator(c)) { // In this case, '(' and ')' are not operators.
if (stk.empty() || priority(c) < priority(stk.top())) {
stk.push(c);
} else {
while (!stk.empty() && c != '(' && c != ')' && priority(c) >= priority(stk.top())) {
result += stk.top();
stk.pop();
}
stk.push(c);
}
} else if (c == '(') {
stk.push(c);
} else if (c == ')') {
while (!stk.empty() && stk.top() != '(') {
result += stk.top();
stk.pop();
}
stk.pop(); // Pop the remaining '('.
} else {
result += c;
}
}
while (!stk.empty()) {
result += stk.top();
stk.pop();
}
return result;
}
bool isoperator(char c) {
if (string("+-*/%").find(c) != string::npos) {
return true;
} else {
return false;
}
}
/* Priority Function
This function is used to determine an operator's priority.
Note that the priority is higher when the function returns a SMALLER value.
*/
int priority(char c) {
if (isoperator(c)) {
switch (c) {
case '*':
case '/':
case '%':
return 3;
case '+':
case '-':
return 4;
}
}
return 9;
}