libds

simple data structures library and utility functions
git clone git://git.2f30.org/libds
Log | Files | Refs | LICENSE

commit 14b7a734b4a11d12aaec3addbd5cdc062b5c1768
parent 1c6a976146697d192bdbf4f16abf37ee6a6f0fcf
Author: sin <sin@2f30.org>
Date:   Tue,  6 May 2014 13:09:23 +0100

Add simple stack implementation

Diffstat:
MMakefile | 2+-
Mds.h | 19+++++++++++++------
Astack.c | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 86 insertions(+), 7 deletions(-)

diff --git a/Makefile b/Makefile @@ -3,7 +3,7 @@ include config.mk -SRC = vector.c fifo.c +SRC = fifo.c stack.c vector.c OBJ = ${SRC:.c=.o} SOUT = ${NAME}.a diff --git a/ds.h b/ds.h @@ -3,6 +3,19 @@ #include <stddef.h> +/* fifo.c */ +struct fifo *fifo_init(size_t); +void fifo_free(struct fifo *); +int fifo_add(struct fifo *, const void *, size_t); +int fifo_remove(struct fifo *, void *, size_t); + +/* stack.c */ +struct stack *stack_init(void); +void stack_free(struct stack *); +void *stack_push(struct stack *, void *); +void *stack_pop(struct stack *); +void *stack_peek(struct stack *); + /* vector.c */ struct vector *vector_init(void); void vector_free(struct vector *); @@ -11,10 +24,4 @@ void *vector_get(struct vector *, size_t); size_t vector_len(struct vector *); void vector_walk(struct vector *, void (*)(struct vector *, void *)); -/* fifo.c */ -struct fifo *fifo_init(size_t); -void fifo_free(struct fifo *); -int fifo_add(struct fifo *, const void *, size_t) -int fifo_remove(struct fifo *, void *, size_t); - #endif diff --git a/stack.c b/stack.c @@ -0,0 +1,72 @@ +#include <stdio.h> +#include <stdlib.h> + +struct stacknode { + void *data; + struct stacknode *next; +}; + +struct stack { + struct stacknode *top; +}; + +struct stack * +stack_init(void) +{ + struct stack *s; + + s = calloc(1, sizeof(*s)); + if (!s) + return NULL; + return s; +} + +void +stack_free(struct stack *s) +{ + struct stacknode *n, *tmp; + + if (s->top) { + n = s->top; + while (n) { + tmp = n->next; + free(tmp); + n = tmp; + } + } + free(s); +} + +void * +stack_push(struct stack *s, void *data) +{ + struct stacknode *n; + + n = calloc(1, sizeof(*n)); + if (!n) + return NULL; + n->data = data; + n->next = s->top; + s->top = n; + return data; +} + +void * +stack_pop(struct stack *s) +{ + void *data; + + if (!s->top) + return NULL; + data = s->top->data; + s->top = s->top->next; + return data; +} + +void * +stack_peek(struct stack *s) +{ + if (!s->top) + return NULL; + return s->top->data; +}