#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isOperator(char c){
if(c=='+' || c=='-' || c=='*' || c=='/' || c=='^')
return true;
return false;
}
int precedence(char c){
if(c=='^')
return 3;
else if(c=='*' || c=='/')
return 2;
else if(c=='+' || c=='-')
return 1;
else
return -1;
}
string InfixToPostfix(stack<char> s, string infix){
string postfix;
for(int i=0;i < infix.size();i++){
char temp=infix[i];
if((temp>='a' && temp<='z')||(temp>='A' && temp<='z')){
postfix+=temp;//if operand arrives, printing the postfix
}
else if(temp=='('){
s.push(temp);//if open parentheses arrives, push in the stack
}
else if(temp==')'){//if closed parenthesis, pop the top and store in postfix expression
while((s.top()!='(') && (!s.empty())){
postfix+=s.top();
s.pop();
}
if((!s.empty()) && (s.top()='(')){//removing the parentheses
s.pop();
}
}
else if(isOperator(temp)){
while((!s.empty()) && (precedence(temp)<=precedence(s.top()))){
if(temp=='^' && s.top()=='^')
break;
else{
postfix+=s.top();
s.pop();
}
}
s.push(temp);//if stack is empty then push the temp character
}
}
while(!s.empty()){//end of the exp, pop all the operators
postfix+=s.top();
s.pop();
}
return postfix;
}
int main() {
stack<char> s;
string infix_exp, postfix_exp;
cout<<"Enter Infix expression: ";
cin>>infix_exp;
cout<<"\nInfix expression is: "<<infix_exp<<endl;
postfix_exp=InfixToPostfix(s,infix_exp);
cout<<"Postfix expression is: "<<postfix_exp<<endl;
return 0;
}