|
14 | 14 | #include <stdio.h> |
15 | 15 |
|
16 | 16 | #define MAX_STACK_SIZE 10 |
17 | | -#define EMPTY (-1) |
18 | 17 | #define STACK_EMPTY INT_MIN |
19 | 18 |
|
20 | | -int stack[MAX_STACK_SIZE]; |
21 | | -int top = EMPTY; |
| 19 | +typedef struct { |
| 20 | + int data[MAX_STACK_SIZE]; |
| 21 | + int top; |
| 22 | +} stack_t; |
22 | 23 |
|
23 | | -bool is_empty() { |
24 | | - return top == EMPTY; |
| 24 | +void stack_init(stack_t* s) { |
| 25 | + s->top = -1; |
25 | 26 | } |
26 | 27 |
|
27 | | -bool is_full() { |
28 | | - return top == MAX_STACK_SIZE - 1; |
| 28 | +bool stack_is_empty(const stack_t* s) { |
| 29 | + return s->top == -1; |
29 | 30 | } |
30 | 31 |
|
31 | | -bool push(int value) { |
32 | | - if (is_full()) { |
| 32 | +bool stack_is_full(const stack_t* s) { |
| 33 | + return s->top == MAX_STACK_SIZE - 1; |
| 34 | +} |
| 35 | + |
| 36 | +bool stack_push(stack_t* s, int value) { |
| 37 | + if (stack_is_full(s)) { |
33 | 38 | return false; |
34 | 39 | } |
35 | | - stack[++top] = value; |
| 40 | + s->data[++s->top] = value; |
36 | 41 | return true; |
37 | 42 | } |
38 | 43 |
|
39 | | -int pop() { |
40 | | - if (is_empty()) { |
41 | | - return STACK_EMPTY; |
| 44 | +bool stack_pop(stack_t* s, int* out) { |
| 45 | + if (stack_is_empty(s)) { |
| 46 | + return false; |
42 | 47 | } |
43 | | - int result = stack[top]; |
44 | | - top--; |
45 | | - return result; |
| 48 | + *out = s->data[s->top--]; |
| 49 | + return true; |
46 | 50 | } |
47 | 51 |
|
48 | | -int main(int argc, char const *argv[]) |
49 | | -{ |
50 | | - int value; |
| 52 | +int main(void) { |
| 53 | + stack_t s; |
| 54 | + stack_init(&s); |
51 | 55 |
|
52 | | - // Test push |
53 | | - for (int i = 0; i < 12; i++) { |
54 | | - if (push(i)) { |
55 | | - printf("Pushed %d onto stack\n", i); |
| 56 | + for (int i = 0; i < 12; ++i) { |
| 57 | + if (stack_push(&s, i)) { |
| 58 | + printf("Pushed %d\n", i); |
56 | 59 | } else { |
57 | | - printf("Stack is full, could not push %d\n", i); |
| 60 | + printf("Stack full, could not push %d\n", i); |
58 | 61 | } |
59 | 62 | } |
60 | 63 |
|
61 | | - // Test pop |
62 | | - for (int i = 0; i < 12; i++) { |
63 | | - value = pop(); |
64 | | - if (value != STACK_EMPTY) { |
65 | | - printf("Popped %d from stack\n", value); |
| 64 | + int value; |
| 65 | + for (int i = 0; i < 12; ++i) { |
| 66 | + if (stack_pop(&s, &value)) { |
| 67 | + printf("Popped %d\n", value); |
66 | 68 | } else { |
67 | | - printf("Stack is empty, could not pop\n"); |
| 69 | + printf("Stack empty, could not pop\n"); |
68 | 70 | } |
69 | 71 | } |
70 | 72 |
|
|
0 commit comments