Infix to postfix using Stack
As i said earlier, I am back with another post and this time around it's STACK time baby. So let's get started with Infix to postfix expression converter using Stacks.
Mind you reader, this blog is for me to remember stuff i need to prepare before my placements so i'll be really up and about in my explanations.
Anyway, let's get started!
#include<bits/stdc++.h>
using namespace std;
//function to print precedence of operators
int precedence(char c)
{
if(c=='^')
return 3;
else if(c=='*' || c=='/')
return 2;
else if(c=='+'|| c== '-')
return 1;
else
return -1;
}
//the function to convert infix to postfix
void intopost(string s)
{
stack<char> st;
string result;
for(int i =0; i<s.length(); i++)
{
char c= s[i];
}
//if the scanned character is operand, add it to output string
if((c>='a' && c< ='z') || (c>='A' && c<='Z') || (c>='0' && c<='9'))
result+=c;
//if the scanned character is a '(' push it in stack
else if(c=='(')
st.push('(');
//if the scanned character is a ')' pop and output until a '(' is seen
else if(c==')')
while(!st.empty() && st.top() != '(')
char temp= st.top();
st.pop();
result+=temp;
st.pop();
//if an operator is scanned
else{
while(!st.empty() && precedence(s[i])<= precendence(st.top()))
char temp= st.top();
st.pop();
result+=temp;
st.push(c);
}
//pop remaining elements
while(!st.empty())
char temp= st.top();
st.pop();
result+=temp;
cout<<result<<endl;
}
int main()
{
string exp;
cin>>exp;
intopost(exp);
return 0;
}
And that's how you convert an Infix to Postfix using a Stack!