
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
struct stk
{
char a[50];
int top;
};
int isempty(struct stk *s);
int isfull(struct stk *s);
main()
{
int i,a,b,r,j;
char exp[50],res[50],c='\0',st[1];
void push(struct stk *s,char item);
char pop(struct stk *s);
struct stk s;
s.top=-1;
printf("Enter the expression: ");
gets(exp);
st[0]=')';
st[1]='\0';
strcat(exp,st);
i=0;
j=0;
while(exp[i]!=0)
{
if(exp[i]=='^'||exp[i]=='+'||exp[i]=='-'||exp[i]=='*'||exp[i]=='/'||exp[i]=='('||exp[i]==')')
{
if(exp[i]=='(')
push(&s,'(');
if(exp[i]=='^'||exp[i]=='+'||exp[i]=='-'||exp[i]=='*'||exp[i]=='/')
{
if(exp[i]=='^')
{
c='\0';
while(1)
{
c=pop(&s);
if(c=='('||c=='*'||c=='/'||c=='+'||c=='-'||c=='\0')
{
push(&s,c);
break;
}
else
{
res[j]=c;
j++;
}
}
}
if(exp[i]=='*'||exp[i]=='/')
{
c='\0';
while(1)
{
c=pop(&s);
if(c=='('||c=='+'||c=='-'||c=='\0')
{
push(&s,c);
break;
}
else
{
res[j]=c;
j++;
}
}
}
if(exp[i]=='+'||exp[i]=='-')
{
c='\0';
while(1)
{
c=pop(&s);
if(c=='('||c=='\0')
{
push(&s,c);
break;
}
else
{
res[j]=c;
j++;
}
}
}
push(&s,exp[i]);
}
if(exp[i]==')')
{
c='\0';
while(1)
{
c=pop(&s);
if(c=='('||c=='\0')
break;
res[j]=c;
j++;
}
}
}
else
{
res[j]=exp[i];
j++;
}
i++;
}
res[j]='\0';
printf("\n Infix exp is %s",exp);
printf("\n Postfix expression is %s",res);
getch();
return 0;
}
void push(struct stk *s,char item)
{
int c;
c=isfull(s);
if(c==0)
{
printf("stack is full. it is not possible to PUSH %c ",item);
return;
}
s->a[++(s->top)]=item;
}
int isfull(struct stk *s)
{
if(s->top==9)
return 0;
return 1;
}
char pop(struct stk *s)
{
int c;
char i;
c=isempty(s);
if(c==0)
{
printf("stack is empty. it is not possible to POP ");
return '\0';
}
i=s->a[(s->top)--];
return i;
}
int isempty(struct stk *s)
{
if(s->top==-1)
return 0;
return 1;
}