forked from aman-raza/Friends_Hack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Infix2Postfix.cpp
77 lines (66 loc) · 1.64 KB
/
Infix2Postfix.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<vector>
using namespace std;
// Checks if operator or not,
// !! If new operator needed, change inside string
bool isOperand(char ch){
for(char i : "+-*/^()"){
if(i == ch) return false;
}
return true; // is not any operator of brackett
}
// Determines priority
int priority(char ch) {
switch (ch) {
case '^' : return 4;
case '/' : return 3;
case '*' : return 2;
case '-' : return 1;
case '+' : return 0;
}
return 6;
}
// Reverse Notation string(POstFix)
string polishString(string expression){
string polishString;
stack<char> stk; // For polish string conversion
for(char ch : expression){
if(isOperand(ch)) {
polishString += ch;
}
else if (ch == '(') {
stk.push(ch); // Push (
}
else if(ch == ')') {
// Pop till '('
char temp = stk.top();
while(temp != '(' ) {
polishString += temp;
stk.pop();
temp = stk.top();
}
stk.pop(); // Remove '('
}
else {
char c = stk.top();
while(priority(ch) > priority(c)){
polishString += c;
stk.pop();
c = stk.top();
}
stk.push(ch);
}
}
return polishString;
}
int main(){
int t;
cin >> t;
while(t--){
string expression;
cin >>expression;
cout << polishString(expression)<< '\n';
}
return 0;
}