-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpn.c
43 lines (34 loc) · 944 Bytes
/
rpn.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
// Licensed under the MIT License.
#include <ctype.h>
#include "rpn.h"
#include "rpn_operator.h"
static RpnOperator rpn_get_operator(Rpn instance, String operator)
{
switch (operator[0])
{
case '+': return instance->add;
case '-': return instance->subtract;
case '*': return instance->multiply;
case '/': return instance->divide;
}
return NULL;
}
double rpn_evaluate(Rpn instance, String tokens[], size_t length)
{
size_t sp = 0;
double* stack = malloc(length * sizeof * stack);
for (size_t i = 0; i < length; i++)
{
if (tokens[i][1] != '\0' || isdigit(tokens[i][0]))
{
stack[sp] = atof(tokens[i]);
sp++;
continue;
}
double left = stack[sp - 2];
double right = stack[sp - 1];
stack[sp - 2] = rpn_get_operator(instance, tokens[i])(left, right);
sp--;
}
return stack[0];
}