-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathinfixToPrefix.cpp
More file actions
36 lines (33 loc) · 990 Bytes
/
infixToPrefix.cpp
File metadata and controls
36 lines (33 loc) · 990 Bytes
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
#include<bits/stdc++.h>
#include<unordered_map>
using namespace std;
string prefix(string str) {
int len=str.length();
stack<char> s;
string res;
unordered_map<char, int> M;
M['+'] = ( M['-'] = 1);
M['*'] = ( M['/'] = 2);
M['^'] = 3;
for(int i=len-1;i>=0;i--) {
if(str[i]>='a' && str[i]<='z') res+=str[i];
else {
if(str[i]==')') s.push(str[i]);
else if(str[i]=='(') {
while(!s.empty() && s.top()!=')'){res+=s.top(); s.pop();}
s.pop();
}
else if(s.empty() || M[s.top()]<M[str[i]]) s.push(str[i]);
else {
while(!s.empty() && (M[s.top()]>M[str[i]] || (M[s.top()]==M[str[i]] && str[i]=='^'))) {res+=s.top(); s.pop();}
s.push(str[i]);
}
}
}
while(!s.empty()) {res+=s.top(); s.pop();}
reverse(res.begin(), res.end());
return res;
}
int main() {
cout<<prefix("(a+b)*c+d-(e/g)^f");
}