Skip to content

Commit 4f97052

Browse files
committed
Infix to Prefix conversion
1 parent b4e71bf commit 4f97052

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
//infix to prefix
2+
#include<iostream>
3+
#include<stack>
4+
#include<string>
5+
#include<algorithm>
6+
using namespace std;
7+
8+
int priority(char op) {
9+
if (op == '^') return 3;
10+
if (op == '*' || op == '/') return 2;
11+
if (op == '+' || op == '-') return 1;
12+
return 0;
13+
}
14+
15+
string infixToPrefix(string &s){
16+
reverse(s.begin(), s.end()); //reversed a string
17+
int i=0;
18+
int n = s.size();
19+
while(i<n){//changing paranthesis
20+
if(s[i]=='('){
21+
s[i] = ')';
22+
}
23+
else if(s[i]==')'){
24+
s[i] = '(';
25+
}
26+
i++;
27+
}
28+
29+
i=0;
30+
string ans = "";
31+
stack<char> st;
32+
while(i<n){
33+
if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z') || (s[i]>='0' && s[i]<='9')){
34+
ans = ans + s[i];
35+
}
36+
else if(s[i] == '('){
37+
st.push(s[i]);
38+
}
39+
else if(s[i] == ')'){
40+
while(!st.empty() && st.top() != '('){
41+
ans += st.top();
42+
st.pop();
43+
}
44+
st.pop();
45+
}
46+
else{
47+
if(s[i] == '^'){
48+
while(!st.empty() && priority(s[i]) <= priority(st.top())){
49+
ans += st.top();
50+
st.pop();
51+
}
52+
}
53+
else{
54+
while(!st.empty() && priority(s[i]) < priority(st.top())){
55+
ans += st.top();
56+
st.pop();
57+
}
58+
}
59+
st.push(s[i]);
60+
}
61+
i++;
62+
}
63+
while(!st.empty()){
64+
ans += st.top();
65+
st.pop();
66+
}
67+
reverse(ans.begin(), ans.end());
68+
return ans;
69+
}
70+
71+
int main() {
72+
string s = "A+B*(C^D-E)^F+G*H-I";
73+
string ans = infixToPrefix(s);
74+
cout<<ans<<endl;
75+
return 0;
76+
}
77+

0 commit comments

Comments
 (0)