-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSTACK_PostfixEvaluation_lab5.c
85 lines (72 loc) · 1.46 KB
/
STACK_PostfixEvaluation_lab5.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
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct StackI
{
int top;
unsigned capacity;
int* arr;
};
struct StackI* createStack( unsigned capacity )
{
struct StackI* stackV = (struct StackI*) malloc(sizeof(struct StackI));
if (!stackV)
return NULL;
stackV->top = -1;
stackV->capacity = capacity;
stackV->arr = (int*) malloc(stackV->capacity * sizeof(int));
if (!stackV->arr)
return NULL;
return stackV;
}
int isEmpty(struct StackI* stackV)
{
return stackV->top == -1 ;
}
char peek(struct StackI* stackV)
{
return stackV->arr[stackV->top];
}
char pop(struct StackI* stackV)
{
if (!isEmpty(stackV))
return stackV->arr[stackV->top--] ;
return '$';
}
void push(struct StackI* stackV, char op)
{
stackV->arr[++stackV->top] = op;
}
int evaluatePostfix(char* exp)
{
struct StackI* stackV = createStack(strlen(exp));
int i;
if (!stackV)
return -1;
for (i = 0; exp[i]; ++i)
{
if (isdigit(exp[i]))
push(stackV, exp[i] - '0');
else
{
int val1 = pop(stackV);
int val2 = pop(stackV);
switch (exp[i])
{
case '+': push(stackV, val2 + val1); break;
case '-': push(stackV, val2 - val1); break;
case '*': push(stackV, val2 * val1); break;
case '/': push(stackV, val2/val1); break;
}
}
}
return pop(stackV);
}
void main()
{
char exp[30];// = "231*+9-";
printf("Enter the postfix Expression: \n");
scanf("%s",&exp);
printf ("postfix evaluation: %d", evaluatePostfix(exp));
}