#include<stdio.h>
#define MAX 20
struct stack
{int top;
char item[MAX];
char *ex;
};
typedef struct stack STACK;
void initstack(STACK *ps)
{ ps->top=-1;
}
int isempty(STACK *ps)
{ return ps->top==-1;
}
void push(STACK *ps,int n)
{ ps->item[++ps->top]=n;
}
char pop(STACK *ps)
{ return ps->item[ps->top--];
}
char stacktop(STACK *ps)
{ return ps->item[ps->top];
}
//CONVERTING INFIX TO POSTFIX USING PRIORITY METHOD
int priority(char ch)
{ switch(ch)
{ case '(':return 0;
case '+':
case '-':return 1;
case '/':
case '%':
case '*':return 2;
}
}
void postfix(char *in,char *post)
{ int i,j=0;
STACK s1;
char ch;
initstack(&s1);
for(i=0;in[i]!='\0';i++)
{ switch(in[i])
{ case '(': push(&s1,in[i]); break;
case 'A':
case 'a':
case 'B':
case 'b':
case 'C':
case 'c':
case 'D':
case 'd': post[j++]=in[i]; break;
case '+':
case '-':
case '/':
case '%':
case '*': if(isempty(&s1) || (priority(in[i])>priority(stacktop(&s1))))
push(&s1,in[i]);
else
{ while(priority(in[i]) <= priority(stacktop(&s1))&&!isempty(&s1))
post[j++]=in[i];
push(&s1,in[i]);
}
break;
case ')': while((ch=pop(&s1))!='(')
post[j++]=ch;
} //switch end
} //for end
while(!isempty(&s1))
post[j++]=pop(&s1);
post[j]='\0';
}
//EVALUATING POSTFIX EXPRESSION
int evaluate(char *post)
{ STACK s1;
int i,vala,valb,valc,vald,op1,op2;
printf("\n ENTER THE VALUES OF a,b,c & d: ");
scanf("%d %d %d %d",&vala,&valb,&valc,&vald);
for(i=0;post[i]!='\0';i++)
{ switch(post[i])
{ case 'a':
case 'A': push(&s1,vala); break;
case 'B':
case 'b': push(&s1,valb);break;
case 'C':
case 'c': push(&s1,valc);break;
case 'D':
case 'd': push(&s1,vald);break;
default: op2=pop(&s1);
op1=pop(&s1);
}
switch(post[i])
{ case '+': push(&s1,op1 + op2); break;
case '-': push(&s1,op1 - op2); break;
case '/': push(&s1,op1 / op2); break;
case '%': push(&s1,op1 % op2); break;
case '*': push(&s1,op1 * op2); break;
}
}
return pop(&s1);
}
void main()
{ char instr[20],poststr[20];
clrscr();
printf("\n ENTER THE INFIX EXPRESSION : ");
gets(instr);
postfix(instr,poststr);
printf("\n POSTFIX EXPRESSION IS : ");
puts(poststr);
printf("\n RESULT = %d",evaluate(poststr));
getch();
}