Monday, June 18, 2012

Evaluation of entered postfix expression using C data Structure


In this program, enter any postfix expression , the expression will be evaluated and the result will be displayed (e.g if the entered expression is 889*-88*- the result will display –128 )

Here are the codes of the program

# include < stdio.h>
# include < stdlib.h>
struct list
{
int num;
struct list *next;
};
struct list *push(int i,struct list *node)
{
struct list *new1;
new1=(struct list *)malloc(sizeof(struct list));
new1->num=i;
new1->next=node;
node=new1;
return node;
}
struct list *pop(struct list *node)
{
struct list *p;
p=node->next;
free(node);
node=p;
return node;
}
void main()
{
struct list *start=NULL;
char c;
int x,y,result;
clrscr();
printf("\nEnter the expression:-");
while((c=getchar())!='\n')
{
if(isdigit(c)!=0)
start=push(c-48,start);
else
{
y=start->num;
start=pop(start);
x=start->num;
start=pop(start);
switch(c)
{
case '+':
{
result=(x+y);
start=push(result,start);
break;
}
case '-':
{
result=(x-y);
start=push(result,start);
break;
}
case '*':
{

result=(x*y);
start=push(result,start);
break;
}
case '/':
{
result=(x/y);
start=push(result,start);
break;
}
}
}
}
printf("Result of the expression is::%d",start->num);
getch();
}

In this program the expression is taken as a string value and each character is checked whether it is digit or non digit. For digits, the element is pushed in a stack and for operators, two elements from the stack are popped from the stack. After evaluating the popped elements according to operator, the result is again pushed on the stack. Ultimately, the stack contains one element and that is the result.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner