This commit is contained in:
Johannes Randerath 2024-05-15 14:14:03 +02:00
parent aeb01f4ee9
commit 2b6b07a3e0
No known key found for this signature in database
GPG Key ID: 57453FDC34C9EE1D
2 changed files with 72 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*.out
*.o

70
stack.c Normal file
View File

@ -0,0 +1,70 @@
#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;
}