-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfixevl.c
124 lines (121 loc) · 2.27 KB
/
postfixevl.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
122
123
124
#include<stdio.h>
#include<string.h>
#define MAX 100
char stack[MAX];
int top = -1;
void push(char x);
int isfull();
int isempty();
char pop();
char peek();
int isoperand(char x);
int convert(char postfix[MAX]);
void main()
{
char postfix[MAX];
printf("ENTER THE POSTFIX EXPRESSION : \n");
gets(postfix);
int result;
result=convert(postfix);
printf("%s = %d \n", postfix, result);
}
void push(char x)
{
stack[++top] = x;
}
int isfull()
{
if(top == MAX-1)
{
return 1;
}
else
{
return 0;
}
}
int isempty()
{
if(top == -1)
{
return 1;
}
else
{
return 0;
}
}
char pop()
{
int c;
c = stack[top--];
return c;
}
char peek()
{
return stack[top];
}
int isoperand(char x)
{
if(x >= '0'&& x <= '9')
{
return 1;
}
else
{
return 0;
}
}
int convert(char postfix[MAX])
{
int operator1, operator2, value;
for(int i = 0; i < strlen(postfix); i++)
{
if(postfix[i]=='A'||postfix[i]=='a')
{
postfix[i]='1';
}
else if(postfix[i]=='B'||postfix[i]=='b')
{
postfix[i]='2';
}
else if(postfix[i]=='C'||postfix[i]=='c')
{
postfix[i]='3';
}
else if(postfix[i]=='D'||postfix[i]=='d')
{
postfix[i]='4';
}
}
for(int i = 0; i < strlen(postfix); i++)
{
if(isoperand(postfix[i]))
{
push((int)postfix[i]-'0');
}
else //for operator
{
operator1 = pop();
operator2 = pop();
if(postfix[i]=='+')
{
value = operator2 + operator1;
}
else if(postfix[i] == '-')
{
value = operator2 - operator1;
}
else if(postfix[i] == '*')
{
value = operator2 * operator1;
}
else
{
value = operator2 / operator1;
}
push(value);
}
}
return pop();
}