Program to Convert Infix to Postfix Expression using Stack

/* Program to convert infix expression in to post fix expression */
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
#define MAX 20
class stack
{
char s[MAX];
int top;
public:
stack()
{
top=-1;
}

void push(char );
char pop();
int isfull();
int isempty();
void display();
void convert(char *str);
int priority(char ch);
};
void stack:: push(char x)
{
if(isfull()==1)
{
cout<<“\n stack full”;
return;
}
else
{
top++;
s[top]=x;
}
}
char stack:: pop()
{
char ele=’\0′;
if(isempty()==1)
{
cout<<“\n stack empty “;
return ele;
}
else
{
ele=s[top];
top–;
}
return ele;
}
void stack::display()
{
int i;
for(i=top;i>=0;i–)
cout<<“\n”<<s[i];
}
int stack:: isempty()
{
int i=0;
if(top==-1)
i=1;
return i;
}
int stack:: isfull()
{
int i=0;
if(top==MAX)
i=1;
return i;
}

void stack:: convert(char *str)
{
char exp[20];
int k=0;
char poped;
while(*str!=’\0′)
{
if(*str=='(‘)
{
push(*str);
str++;
}
else if( isalpha(*str) || isdigit(*str))
{
exp[k]=*str;
k++;
str++;
}
else if(*str==’)’)
{
poped=pop();
while(poped!='(‘)
{
exp[k]=poped;
k++;
poped=pop();
}
str++;
}
else if(*str==’+’|| *str==’*’|| *str==’+’|| *str==’-‘|| *str==’/’||*str==’%’||*str==’^’)
{
if(top!=-1)
{
poped=pop();
if(poped=='(‘)
{
push(poped);
push(*str);
str++;
continue;
}
if (priority(poped)>=priority(*str))
{
exp[k]=poped;
k++;
poped=pop();
}
push(poped);
push(*str);
}
else
{
push(*str);
}
str++;
}
}
exp[k]=’\0′;
cout<<“postfix string is “<<exp;
}

int stack :: priority(char ch)
{
if(ch==’^’||ch==’$’)
return 3;
else if(ch==’*’||ch==’/’|| ch==’%’)
return 2;
else if(ch==’+’ || ch==’-‘)
return 1;
else
return 4;
}

void main()
{
stack st1;
char exp[20];
clrscr();
cout<<“\n enter expression “;
cin>>exp;
st1.convert(exp);
getch();
}

Leave a Reply