diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..de74700 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.out +*.o diff --git a/stack.c b/stack.c new file mode 100644 index 0000000..703648d --- /dev/null +++ b/stack.c @@ -0,0 +1,70 @@ +#include +#include +#include +#include + +typedef struct node { + void *content; + struct node *next; +}Node; + +typedef struct stack { + Node *top; + size_t w; +}Stack; + +Stack *new_stack(size_t w) { + Stack *s = malloc(sizeof(Stack)); + s->top = NULL; + s->w = w; + return s; +} + +bool is_empty(Stack *s) { + return !s->top; +} + +void push(void *content, Stack *s) { + Node *n = malloc(sizeof(Node)); + n->content = malloc(s->w); + mempcpy(n->content, content, s->w); + n->next = s->top; + s->top = n; +} + +void *pop(Stack *s) { + if (is_empty(s)) + return NULL; + void *r = s->top->content; + Node *n = s->top; + s->top = s->top->next; + free(n); + return r; +} + +void destroy(Stack *s) { + while (!is_empty(s)) { + free(s->top->content); + pop(s); + } +} + +int main() { + Stack *s = new_stack(sizeof(int)); + int *a = malloc(sizeof(int)); + int *b = malloc(sizeof(int)); + int *c = malloc(sizeof(int)); + int *d = malloc(sizeof(int)); + *a=1; + *b=2; + *c=3; + *d=-1; + push(a, s); + push(b, s); + push(c, s); + push(d, s); + destroy(s); + printf("%d\n", is_empty(s)); + return 0; +} +