forked from ShreyaDhir/HacktoberFest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Eval_Postfix.c
94 lines (86 loc) · 1.61 KB
/
Eval_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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*EVALUATING A POSTFIX EXPRESSION
Author:Debargha Mukherjee
GitHub: https://github.com/Debargha-arch
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max 50
//A Stack ADT created for maintaining the expression
struct stack
{
char s[max];
int top;
};
//Function for postfix evaluation
int eval_postfix(struct stack *p,char exp[max])
{
int i;
int n=strlen(exp);
exp[n]=')';
for(i=0;exp[i]!=')';i++)
{
if(isdigit(exp[i]))
push(p,exp[i]-'0');
else
{
int op1=pop(p);
int op2=pop(p);
switch(exp[i])
{
case '+':
push(p,op2+op1);
break;
case '-':
push(p,op2-op1);
break;
case '*':
push(p,op2*op1);
break;
case '/':
push(p,op2/op1);
break;
}
}
}
return pop(p);
}
//Function to push element into a stack
void push(struct stack *p,int n)
{
if((*p).top==max-1)
{
printf("\nOVERFLOW\n");
}
else
{
((*p).top)++;
(*p).s[(*p).top]=n;
}
}
//Function to pop/remove element from a stack
int pop(struct stack *p)
{
int n;
if((*p).top==-1)
{
printf("\nUNDERFLOW\n");
return 0;
}
else
{
n=(*p).s[(*p).top];
((*p).top)--;
return n;
}
}
int main()
{
struct stack p;
p.top=-1;
char exp[max];
printf("Enter Postfix Expression:\n");
gets(exp);
int a=eval_postfix(&p,exp); //the poped element returned is stored in integer variable a
printf("\nThe Evaluated Expression: %d",a);
}