#include"conio.h"
#include"alloc.h"
#define MAX 50
struct stack
{
int top;
char data[MAX];
};
typedef struct stack stack;
void push(stack *,char);
char pop(stack *);
int prec_stack(char c);
int prec(char c);
void infix_postfix_par(char *i,char *p);
void main()
{
char i[20],p[20];
clrscr();
printf("Enter a infix string>");
gets(i);
strcat(i,")");
infix_postfix_par(i,p);
printf("\nPostfix is : %s",p);
getch();
}
void infix_postfix_par(char *i,char *p)
{
stack st;
char next,t,*in=i;
st.top=-1;
push(&st,'(');
next=*in;
while(next!='\0')
{
while(prec(next)
t=pop(&st);
*p=t;
p++;
}
if(prec(next)!=prec_stack(st.data[st.top]))
push(&st,next);
else
pop(&st);
in++;
next=*in;
}
while(st.top>=0)
{
t=pop(&st);
*p=t;
p++;
}
}
void push(stack *st,char data)
{
if(st->top==MAX-1)
{
printf("\nList is Already FULL");
return;
}
st->data[++st->top]=data;
}
char pop(stack *st)
{
char res;
if(st->top==-1)
{
printf("\nList is Empty");
return NULL;
}
res=st->data[st->top];
st->top--;
return res;
}
int prec(char c)
{
if(c=='#' || c==')')
return 0;
else if(c=='*' || c=='/')
return (3);
else if(c=='+' || c=='-')
return (1);
else if(c=='^')
return (6);
else if(c=='(')
return(9);
else
return(7);
}
int prec_stack(char c)
{
if(c=='(')
return 0;
else if(c=='*' || c=='/')
return (4);
else if(c=='+' || c=='-')
return (2);
else if(c=='^')
return (5);
else if(c==')')
return(0);
else
return(8);
}
No comments:
Post a Comment