codintuni/stack.c
Johannes Randerath 2b6b07a3e0
Stack
2024-05-15 14:14:03 +02:00

71 lines
1.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
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;
}