-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevaluation of postfix.c
64 lines (59 loc) · 1.36 KB
/
evaluation of postfix.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//evaluation of postfix expression
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include "arraystackadt.h"
bool isoperator(char token)
{
if(token=='*'||token=='/'||token=='+'||token=='-')
return true;
return false;
}
int calculate(int opd1,int opd2,char token)
{
switch(token)
{
case '+':return(opd1+opd2);
case '-':return(opd1-opd2);
case '*':return(opd1*opd2);
case '/':return(opd1/opd2);
default: return 0;
}
}
int main()
{
int opd1,opd2,result,i=0;
int *pd;
AST *ph;
char postfix[25],token;
ph=(AST*)createstack();
printf("enter the postfix expression to evaluate:\n");
scanf("%s",postfix);
while(postfix[i]!='\0')
{
token=postfix[i];
if(isoperator(postfix[i]))
{
pd=(int*)popstack(ph);
opd2=*pd;
free(pd);
pd=(int*)popstack(ph);
opd1=*pd;
result=calculate(opd1,opd2,token);
*pd=result;
pushstack(ph,pd);
}
else
{
pd=(int*)malloc(sizeof(int));
*pd=postfix[i]-'0';
pushstack(ph,pd);
}
i++;
}
pd=(int*)popstack(ph);
printf("Result=%d",*pd);
free(pd);
destory(ph);
return 0;
}