Skip to content

Commit 3a96761

Browse files
committed
Update stack_array.c
1 parent c9231eb commit 3a96761

File tree

1 file changed

+32
-30
lines changed

1 file changed

+32
-30
lines changed

Stack/stack_array.c

Lines changed: 32 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -14,57 +14,59 @@
1414
#include <stdio.h>
1515

1616
#define MAX_STACK_SIZE 10
17-
#define EMPTY (-1)
1817
#define STACK_EMPTY INT_MIN
1918

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;
2223

23-
bool is_empty() {
24-
return top == EMPTY;
24+
void stack_init(stack_t* s) {
25+
s->top = -1;
2526
}
2627

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;
2930
}
3031

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)) {
3338
return false;
3439
}
35-
stack[++top] = value;
40+
s->data[++s->top] = value;
3641
return true;
3742
}
3843

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;
4247
}
43-
int result = stack[top];
44-
top--;
45-
return result;
48+
*out = s->data[s->top--];
49+
return true;
4650
}
4751

48-
int main(int argc, char const *argv[])
49-
{
50-
int value;
52+
int main(void) {
53+
stack_t s;
54+
stack_init(&s);
5155

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);
5659
} else {
57-
printf("Stack is full, could not push %d\n", i);
60+
printf("Stack full, could not push %d\n", i);
5861
}
5962
}
6063

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);
6668
} else {
67-
printf("Stack is empty, could not pop\n");
69+
printf("Stack empty, could not pop\n");
6870
}
6971
}
7072

0 commit comments

Comments
 (0)