-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
92 lines (86 loc) · 2.08 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
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "stack.h"
bstack *
init () {
bstack *stack = malloc(sizeof(bstack));
stack->used = 0;
stack->size = 64;
stack->stack = malloc((stack->size)*sizeof(char));
return stack;
}
void
freeStack (bstack *stack) {
free(stack->stack);
free(stack);
}
void
push (bstack *stack, int val) {
if (stack->used == stack->size) {
stack->stack = realloc(stack->stack, 2*(stack->size));
if (!(stack->stack))
exit(0);
}
stack->stack[(stack->used)++] = val;
}
int
pop (bstack *stack) {
assert (stack->used > 0);
return stack->stack[--(stack->used)];
}
void
fungePush (bstack *stack, int val) {
if (val < 10) {
push(stack, val);
} else if (val == '+') {
push(stack, pop(stack) + pop(stack));
} else if (val == '-') {
push(stack, -pop(stack) + pop(stack));
} else if (val == '*') {
push(stack, pop(stack) * pop(stack));
} else if (val == '/') {
int a = pop(stack);
int b = pop(stack);
push(stack, b/a);
} else if (val == '%') {
int a = pop(stack);
int b = pop(stack);
push(stack, b%a);
} else if (val == '!') {
push(stack, !pop(stack));
} else if (val == '`') {
int a = pop(stack);
int b = pop(stack);
push(stack, (b>a) ? 1 : 0);
} else if (val == ':') {
int a = pop(stack);
push(stack, a);
push(stack, a);
} else if (val == '\\') {
int a = pop(stack);
int b = pop(stack);
push(stack, a); push(stack, b);
} else if (val == '$') {
pop(stack);
} else if (val == '&') {
int num;
scanf("%d", &num);
push(stack, num);
} else if (val == '~') {
char num;
scanf("%c", &num);
push(stack, num);
}
}
/* for testing
int
main (int argc, char *argv[]) {
bstack *stack = init();
for (int i = 0; i < 10; ++i)
push(stack, i);
for (int i = 0; i < 10; ++i)
printf("%d\n", pop(stack));
freeStack(stack);
}
*/