-
Notifications
You must be signed in to change notification settings - Fork 1
/
Postfix_evaluation_using_stack.c
121 lines (121 loc) · 2.26 KB
/
Postfix_evaluation_using_stack.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stack // operands are numbers in character data type form.
{
int size;
int top;
int *A;
};
void create(struct stack *s, char A[])
{
(*(s)).size = strlen(A) + 1;
(*(s)).top = (-1);
(*(s)).A = (int *)malloc((*(s)).size * sizeof(int));
}
void push(struct stack *s, int b)
{
if ((*(s)).top == (*(s)).size - 1)
{
printf("Stack overflow!\n");
}
else
{
(*(s)).top++;
(*(s)).A[(*(s)).top] = b;
}
}
int pop(struct stack *s)
{
int c = (-1);
if ((*(s)).top == (-1))
{
return c;
}
else
{
c = (*(s)).A[(*(s)).top];
(*(s)).top--;
return c;
}
}
int stacktop(struct stack *s)
{
int c = (-1);
if ((*(s)).top == (-1))
{
return c;
}
else
{
c = (*(s)).A[(*(s)).top];
return c;
}
}
int isempty(struct stack *s)
{
if ((*(s)).top == (-1))
{
return 1;
}
else
{
return 0;
}
}
int isoperand(char c)
{
if (c == '+' || c == '-' || c == '*' || c == '/')
{
return 0;
}
else
{
return 1;
}
}
int postfix_evaluation(struct stack *s, char A[])
{
int r;
int x1, x2;
for (int i = 0; A[i] != '\0'; i++)
{
if (isoperand(A[i]) == 1)
{
push(s, A[i] - '0');
}
else
{
x2 = pop(s); // integer data type
x1 = pop(s); // integer data type
switch (A[i])
{
case '+':
push(s, x1 + x2);
break;
case '-':
push(s, x1 - x2);
break;
case '*':
push(s, x1 * x2);
break;
case '/':
push(s, (x1 / x2));
break;
}
}
}
r = stacktop(s);
return r;
}
int main()
{
struct stack s;
printf("Enter the expression:\n");
char A[100];
gets(A);
printf("\nEntered expression is:\n");
puts(A);
create(&s, A);
printf("\nValue of postfix expression is %d.\n", postfix_evaluation(&s, A));
}