C program to evaluate the postfix expression using stack

0
766

C program to evaluate the postfix expression using stack

CONSTRUCTION:

  1. Define the stack structure & read an expression.
  2. While not reaching the null character recursively process the following steps

If the character is operand then convert into ASCII value and push the                       numerical value into the top of the stack.

If the character is operator then pop the top two element from the stack.

Perform the mathematical expression related to the operator between the                        operand.

Push the resultant value into the top of the stack.

Increment the loop value by 1.

  1. Display the top element in the stack.
  2. Stop the program.

PROGRAM

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<process.h>
struct node
{
 int data;
 struct node *next;
}*top=NULL,*newnode;
int push(int);
void main()
{
 int a,b,n,x,i;
 char p[20];
 i=0;
 clrscr();
 printf("enter any mathematical expression");
 scanf("%s",p);
 while(p[i]!='\0')
 {
 if(p[i]=='+'||p[i]=='-'||p[i]=='*'||p[i]=='/')
 {

 b=pop();
 a=pop();
 switch(p[i])
 {
 case'+':
 push(a+b);
 break;
 case'-':
 push(a-b);
 break;
 case'*':
 push(a*b);
 break;
 case'/':
 push(a/b);
 break;
 }
 }
 else
 {
 printf("enter the value for %c",p[i]);
 scanf("%d",&x);
 push(x);
 }
 i++;
 }
 printf("result=%d",top->data);
 getch();
}

int push(int n)
{
 newnode=(struct node*)malloc(sizeof(struct node));
 newnode->data= n;
 newnode->next=top;
 top=newnode;
 return top;
}
int pop()
{
 int t;
 t= top->data;
 top=top->next;
 return t;
}

 

 

 

Leave a Reply