-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathINPSTFIX.cpp
More file actions
47 lines (45 loc) · 1.01 KB
/
Copy pathINPSTFIX.cpp
File metadata and controls
47 lines (45 loc) · 1.01 KB
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
#include <bits/stdc++.h>
using namespace std;
int prec(char op){
if(op == '^') return 3;
else if(op == '*' or op == '/') return 2;
else if(op == '+' or op == '-') return 1;
else return 0;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t, n;
string infix;
cin>>t;
while(t--){
cin>>n;
cin>>infix;
stack<char> s;
string postfix;
for(int i=0;i<n;i++){
if(infix[i] == '(') s.push(infix[i]);
else if(isalpha(infix[i])) postfix += infix[i];
else if(infix[i] == ')'){
while(s.top() != '('){
postfix += s.top();
s.pop();
}
s.pop();
}
else{
while(!s.empty() and prec(infix[i])<=prec(s.top())){
postfix += s.top();
s.pop();
}
s.push(infix[i]);
}
}
while(!s.empty()){
postfix += s.top();
s.pop();
}
cout<<postfix<<"\n";
}
return 0;
}