Skip to content

Instantly share code, notes, and snippets.

@shemul
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shemul/779ddd5edecf449454da to your computer and use it in GitHub Desktop.
Save shemul/779ddd5edecf449454da to your computer and use it in GitHub Desktop.
infix to postfix by Mam
// This program will convert an
//infix expression to postfix expression.
//Shemul Hossain
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int priority(char x)
{
switch(x)
{
case '(':
case '#':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
}
}
int main()
{
//char infix[20]={'2','*','3','/','(','2','-','1',')','+','5','*','3','\0'}, postfix[20], c;
string infix;
char postfix[20],c;
int i,k=0;
stack<char>st;
st.push('#');
cout<< "Enter your infix expression here: "<<endl;
cin>>infix;
for(i=0; infix[i]!='\0'; i++)
{
c = infix[i];
if(c == '(')
{
st.push(c);
}
else if (c==')')
{
while(st.top()!='(')
{
postfix[k++]=st.top();
st.pop();
}
st.pop();
}
else if (c=='+' || c=='-' || c=='*' || c=='/' || c=='%' )
{
while (priority(c)<=priority(st.top()))
{
if(st.top()!='#')
{
postfix[k++]=st.top();
}
st.pop();
}
st.push(c);
}
else
{
postfix[k++]=c;
}
}
while(!st.empty())
{
postfix[k++]=st.top();
st.pop();
}
postfix[k]='\0';
cout<<"Converted Postfix expression: "<<endl;
for(int i=0; postfix[i]!='\0'; i++)
{
cout<<postfix[i];
}
cout<<endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment