APPLICATION OF STACK ADT - EVALUATING POSTFIX EXPRESSION


SOURCE CODE:

“Pexp.h” File:

#include<stdio.h>
#include<alloc.h>   
#include<conio.h>
struct node
{
   int data;
   struct node *next;
};
typedef struct node *ptrtonode;
typedef ptrtonode STACK1;
typedef ptrtonode position;
STACK1 CreateStack(void)
{
  STACK1 S;
  S=(struct node*)malloc(sizeof(struct node));
  if(S==NULL)
    printf("\nFATAL Error");
  else
  {
    S->next=NULL;
    printf("\nstack created");
  }
  return S;
}
void PushStack(int x,STACK1 S)
{
  ptrtonode temp;
  temp=(struct node*)malloc(sizeof(struct node));
  if(temp==NULL)
    printf("\nFATAL ERROR.");
  else
  {
    temp->data=x;
    temp->next=S->next;
    S->next=temp;
  }
}
int IsEmpty(STACK1 S)
{
  return S->next==NULL;
}
int PopStack(STACK1 S)
{
  int x;
  ptrtonode first;
  if(IsEmpty(S))
    printf("\nTHE STACK IS EMPTY");
  else
  {
    first=S->next;
    x=first->data;
    S->next=S->next->next;
    free(first);
  }
  return x;
}
void MakeEmpty(STACK1 S)
{
  while(!IsEmpty(S))
  PopStack(S);
}
void DisposeStack(STACK1 S)
{
  MakeEmpty(S);
  free(S);
}
void display(STACK1 S)
{
  S=S->next;
  while(S!=NULL)
  {
    printf("%d",S->data);
    printf("\n");
    S=S->next;
  }
}

“Postfix.h” File:

#include"Pexp.h"
#include<ctype.h>
void PostfixEx(char instr[])
{
  STACK1 S=NULL;
  int s=0,x,x1,x2;
  char ch;
  S=CreateStack();
  while((ch=instr[s++])!=NULL)
  {
    if(tolower(ch)>='a'&&tolower(ch)<='z')
    {
      printf("\nEnter the value for %c=",ch);
      scanf("%d",&x);
      PushStack(x,S);
    }
  else
  {
    x1=PopStack(S);
    x2=PopStack(S);
    switch(ch)
    {
    case '+':
    x=x1+x2;
    break;
    case '*':
    x=x1*x2;
    break;
    case '/':
    x=x1/x2;
    break;
    case '-':
    x=x1-x2;
    break;
    case '%':
    x=x1%x2;
    break;
    default:
    printf("\nExpression is wrong");
    }
    PushStack(x,S);
  }
}
x=PopStack(S);
if(S->next==NULL)
     printf("\nAfter evaluated..%d",x);
else
     printf("\nError in expression");
DisposeStack(S);
}

“Postfix.c” File:

#include"postfix.h"
void main()
{
  char instr[10];
  clrscr();
  printf("\nEnter the expression..");
  scanf("%s",instr);
  PostfixEx(instr);
  getch();
}

OUTPUT:
Enter the expression    abcd+e*+f+*
Stack created

Enter the value for a=6

Enter the value for b=5

Enter the value for c=2

Enter the value for d=3

Enter the value for e=8

Enter the value for f=3

After evaluated:    288
Previous
Next Post »

Still not found what you are looking for? Try again here.