#include<bits/stdc++.h>
using namespace std;
int prec(char c){
if(c=='^'){
return 3;
}else if(c=='*' || c=='/'){
return 2;
}else if(c=='+' || c=='-'){
return 1;
}
return -1;
}
string infixToPostfix(string );
int main(){
string s = "(a-b/c)*(a/k-l)";
cout<<infixToPostfix(s);
return 0;
}
string infixToPostfix(string s){
stack<char> st;
string res = "";
for(int i=0;i<s.length();i++){
if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){
res+=s[i];
}else if(s[i]=='('){
st.push(s[i]);
}else if(s[i]==')'){
while((!st.empty()) && st.top()!='('){
res+=st.top();
st.pop();
}
if(!st.empty()){
st.pop();
}
}else{
while((!st.empty()) && prec(st.top())>prec(s[i])){
res+=st.top();
st.pop();
}
st.push(s[i]);
}
while(!st.empty()){
res+=st.top();
st.pop();
}
}
return res;
}
As you can see I'm trying to convert infix notation to postfix notation but the output is not coming as expected. I couldn't even find any syntax error so there's a high chance that there is some logical error.
Expected Output:
abc/-ak/l-*
Actual Output:
(a-b/c*(a/k-l
I have blown my brain off trying to find the error and I still haven't. Please help me solve the issue.