#include"stdio.h"
#include"conio.h"
#include"alloc.h"
#define N 20
typedef struct tree
{
int data;
struct tree *left;
struct tree *right;
}tree;
typedef struct stack
{
char data[N];
int top;
}stack;
typedef struct stack_num
{
tree *data[N];
int top;
}stack_num;
void convert(char *exp,tree **t);
void push(stack *st,char ch);
void push_num(stack_num *st,tree *t);
char pop(stack *st);
tree *pop_num(stack_num *st);
int prec(char c);
int prec_stack(char c);
void display(tree *t);
int eval(tree *t);
int main()
{
char *exp;
tree *t;
clrscr();
printf("Enter the Expression >");
scanf("%s",exp);
convert(exp,&t);
display(t);
printf("\nEval = %d",eval(t));
getch();
return(0);
}
void convert(char *exp,tree **t)
{
stack st_op;
stack_num st_num;
char u;
st_op.top=-1;
st_num.top=-1;
push(&st_op,'(');
u=*exp;
while(u!='\0')
{
if((u>=48 && u <=57) || (u>=65 && u<=122))
{
*t=(tree *)malloc(sizeof(tree));
(*t)->data=u;
(*t)->left=(*t)->right=NULL;
push_num(&st_num,*t);
}
else if(u==')')
{
while(st_op.data[st_op.top]!='(')
{
*t=(tree *)malloc(sizeof(tree));
(*t)->data=pop(&st_op);
(*t)->left=pop_num(&st_num);
(*t)->right=pop_num(&st_num);
push_num(&st_num,*t);
}
}
else if(prec(u)< prec_stack(st_op.data[st_op.top]))
{
*t=(tree *)malloc(sizeof(tree));
(*t)->data=pop(&st_op);
(*t)->left=pop_num(&st_num);
(*t)->right=pop_num(&st_num);
push_num(&st_num,*t);
push(&st_op,u);
}
else
push(&st_op,u);
exp++;
u=*exp;
}
}
void push(stack *st,char ch)
{
if(st->top==N-1)
{
printf("\nStack is Full!!!");
return;
}
st->top++;
st->data[st->top]=ch;
}
char pop(stack *st)
{
char ch;
if(st->top==-1)
{
printf("\nStack is empty!!!");
return(' ');
}
ch=st->data[st->top];
st->top--;
return(ch);
}
void push_num(stack_num *st,tree *t)
{
if(st->top==N-1)
{
printf("\nStack is Full!!!");
return;
}
st->top++;
st->data[st->top]=t;
}
tree *pop_num(stack_num *st)
{
tree *t;
if(st->top==-1)
{
printf("\nStack is empty!!!");
return(NULL);
}
t=st->data[st->top];
st->top--;
return(t);
}
int prec(char c)
{
if(c=='+'||c=='-')
return(1);
else if(c=='*'||c=='/')
return(2);
else if(c=='(')
return(9);
else
return(7);
}
int prec_stack(char c)
{
if(c=='+'||c=='-')
return(2);
else if(c=='*'||c=='/')
return(4);
else if(c=='(')
return(0);
else
return(8);
}
void display(tree *t)
{
if(t!=NULL)
{
display(t->left);
printf("%c ",t->data);
display(t->right);
}
}
int eval(tree *t)
{
if(t->data>=48 && t->data <=57)
{
return(t->data-48);
}
else if(t->data=='+')
{
return(eval(t->left)+eval(t->right));
}
else if(t->data=='-')
{
return(eval(t->left)-eval(t->right));
}
else if(t->data=='*')
{
return(eval(t->left)*eval(t->right));
}
else if(t->data=='/')
{
return(eval(t->left)/eval(t->right));
}
else
{
printf("\nInvalid Operation!!!");
return(0);
}
}
No comments:
Post a Comment