-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.c
305 lines (255 loc) · 8.98 KB
/
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#include "stack.h"
#include "helpers.h"
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include "tree.h"
////-----------------------------------------------------------------------------------------
//------------------------------------------------------------------------ Initializing Stack
stack *initialize()
{
stack *s=malloc(sizeof(stack));
s->top=0;
return s;
}
////-----------------------------------------------------------------------------------------
//------------------------------------------------------------------- Push Item To Last Index
void push(stack *s,Item value)
{
s->items[s->top++]=value;
//adding item in the last index
}
//-----------------------------------------------------------------------------------------
//----------------------------------------------------------- Pop/Remove Last Item In Stack
Item pop(stack *s)
{
Item value;
s->top--;
value = s->items[s->top];
return value;
//removing the last element in the
}
//-----------------------------------------------------------------------------------------
//---------------------------------------------------------- Peek/Return Last Item In Stack
Item peek(stack *s)
{
return s->items[s->top-1];
//returning the last element in the stack
}
//-----------------------------------------------------------------------------------------
//---------------------------------------------------------------- Checks If Stack Is Empty
int isEmpty(stack *s)
{
if(s->top==0)
return 1;
else
return 0;
//check if the is empty
}
////-----------------------------------------------------------------------------------------
//------------------------------------- Calculates According To The Function Of Each Operator
float calculate (char x,float op1,float op2)
{
switch (x)
{
case '+':return op1+op2;
case '-':return op1-op2;
case '/':return op1/op2;
case '*':return op1*op2;
case '%':return (float)((int)op1%(int)op2);
case '^':return powf(op1,op2);
default: return 0;
}
}
//-----------------------------------------------------------------------------------------
//---------------------------------------------------------- Checks If An Operator Is Found
int isOperator(const char* character)
{
switch (character[0])
{
case '-':case '+':case '/':case '*':case '^':case '%':case '(':case ')': return 1;
default: return 0;
}
}
//-----------------------------------------------------------------------------------------
//---------------------------------------------------- Assigns Precedence for each operator
int precedence(char c)
{
switch (c)
{
case '+':return 2;
case '-':return 1;
case '/':return 3;
case '*':return 4;
case '^':return 5;
case '(':case ')':return 6;
default:return -99999;
}
}
//-----------------------------------------------------------------------------------------
//-------------------------------------------------------- Evaluates The PostFix Expression
float evaluate_postfix(char *expression,Node *root)
{
stack *s=initialize();
Item i1,i2,value;
float op1,op2,val;
char *token=strtok(expression," ");
// loop through the string to extract all the other tokens
while( token )
{
//If An Operator is Found:
if(strlen(token)==1 && isOperator(token))
{
//POP The Operand From stack, Calculate the operation & push the value
i2=pop(s);op2=i2.fData;
i1=pop(s);op1=i1.fData;
val=calculate(token[0],op1,op2);
value.fData = val;
push(s,value);
}
else
{
//If 1st element of Token Is a Letter (variable found):
if (isalpha(token[0]))
{
//Search For This Variable
Node *n=search(root,token);
//If Variable Not Found:
if (!n)
{
//Prints an Error Alert for The User That Variable is Not Found
ERROR("[Stack Evaluation]:Variable \"%s\" NOT FOUND !",token);
exit(-1);
}
//Assign The Value of The Variable To fData of operand
i1.fData=n->value;
}
else i1.fData=strtof(token,NULL);
//Push The Value to the Stack
push(s,i1);
}
token = strtok(NULL, " ");
}
//Pop Value From Stack until stack is Empty
value = pop(s);val = value.fData;
//If Stack Is Still Not Empty:
if (!isEmpty(s))
//Prints an Error Alert for The User That Expression Is Invalid
ERROR("[Stack Evaluation]:INVALID EXPRESSION EVALUATED");
free(s);
//Returns the Evaluated PostFix Value Of Expression
return val;
}
//-----------------------------------------------------------------------------------------
//------------------------------------------------- Puts The Expression In The Right Format
char* format(char *expression)
{
VERBOSE("[Format] Formatting The Expression");
VERBOSE("[Format] Before \"%s\"",expression);
//Allocating Double its Size For The WorstCase Compressed Equation
char *formattedRHS=malloc(strlen(expression) * 2);
//Clearing the Formatted RHS String
strcpy(formattedRHS, "");
for(int i=0;i<strlen(expression);i++)
{
char c=expression[i];
//If '-' is Considered As a Negative Sign Not an Operator:
if(( c == '-' && (i==0||isOperator(&expression[i-1])))||(!isOperator(&c)))
{
//Concatenates The '-' To The Formatted RHS String
strncat(formattedRHS, &c, 1);
}
else
{
//Concatenates Operands & Operators To The Formatted RHS String & Adding Spaces
strcat(formattedRHS, " ");
strncat(formattedRHS, &c, 1);
strcat(formattedRHS, " ");
}
}
//ReAllocating To The Proper Size Of The String
formattedRHS = (char*)realloc(formattedRHS, strlen(formattedRHS)+1);
VERBOSE("[Format] After \"%s\"",formattedRHS);
//Return The Formatted Expression with Spaces
return formattedRHS;
}
//-----------------------------------------------------------------------------------------
//------------------------------------ Reform & Change The Expression From InFix to PostFix
char * infixToPost(char *infix)
{
int i = 0;
stack *s = initialize();
VERBOSE("[infixToPost] Stack Initialized");
//Initiate:
VERBOSE("[infixToPost] infix \"%s\" ",infix);
char *postfix=malloc(strlen(infix)+1);
strcpy(postfix,"");
char *token=strtok(infix," ");
//Loop Through The String To Extract All The Other Tokens
while(token)
{
//If An Operator Is Found:
if(strlen(token)==1 && isOperator(token))
{
Item myItem ;
char op[]=" ";
VERBOSE("[infixToPost %d] Operator [%c]",i++,token[0]);
myItem.cData = token[0];
if (token[0]==')')
{
while(peek(s).cData != '(' && !isEmpty(s))
{
VERBOSE("[infixToPost %d] peek [%c]",i++,peek(s).cData);
op[0] = pop(s).cData;
strcat(postfix,op);
strcat(postfix," ");
op[0] = ' ';
}
pop(s);
}
else if (isEmpty(s) || precedence(token[0]) > precedence(peek(s).cData) || (!isEmpty(s) && peek(s).cData == '('))
{
VERBOSE("[infixToPost %d] [%c] precedence %d | isEmpty %d "
, i++, myItem.cData, precedence(myItem.cData),isEmpty(s));
push(s, myItem);
VERBOSE("[infixToPost %d] Pushed %c ",i++,peek(s).cData);
}
else if (precedence(token[0])<=precedence(peek(s).cData))
{
VERBOSE("[infixToPost %d] [%c] precedence %d < %d | isEmpty %d ",
i++,myItem.cData, precedence(myItem.cData), precedence(peek(s).cData),isEmpty(s));
while(precedence(token[0])<=precedence(peek(s).cData) && !isEmpty(s))
{
op[0] = pop(s).cData;
strcat(postfix,op);
strcat(postfix," ");
op[0] = ' ';
}
push(s, myItem);
}
}
//Operand Is Found:
else
{
VERBOSE("[infixToPost %d] Operand [%s] ",i++,token);
strcat(postfix,token);
strcat(postfix," ");
}
token = strtok(NULL, " ");
}
// Popping All The Stack
char op[]=" ";
while (!isEmpty(s))
{
op[0] = pop(s).cData;
strcat(postfix,op);
strcat(postfix," ");
op[0] = ' ';
}
VERBOSE("[infixToPost] Stack is Empty");
free(s);
VERBOSE("[infixToPost] Stack Freed");
VERBOSE("[infixToPost] Postfix: %s",postfix);
return postfix;
}