one-file-projects/stack.c

74 lines
1.3 KiB
C

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
typedef int bool;
#define true 1
#define false 0
struct stack {
int top;
int *data;
int size;
};
void stack_push(struct stack *s, int e);
int stack_pop(struct stack *s);
bool stack_empty(struct stack *s);
bool stack_full(struct stack *s);
void stack_clear(struct stack *s);
void stack_free(struct stack* s);
struct stack* stack_create(int size) {
struct stack* s = (struct stack*)malloc(sizeof(struct stack));
s->top = -1;
s->data = (int*)malloc(sizeof(int)*size);
s->size = size;
return s;
}
void stack_push(struct stack *s, int e) {
assert(!stack_full(s));
s->data[++s->top] = e;
}
int stack_pop(struct stack *s) {
assert(!stack_empty(s));
return s->data[s->top--];
}
bool stack_empty(struct stack *s) {
return (s->top == -1);
}
bool stack_full(struct stack *s) {
return (s->top == s->size - 1);
}
void stack_clear(struct stack *s) {
s->top = -1;
}
void stack_free(struct stack* s) {
free(s->data);
free(s);
}
int main( int argc, char *argv[] ) {
struct stack* s = stack_create(10);
for(int i = 0; !stack_full(s); i++) {
stack_push(s, i);
}
while(!stack_empty(s)) {
printf("%d\n",stack_pop(s));
}
stack_free(s);
s = NULL;
return 0;
}