libds

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

stack.c (922B)


      1 #include <stdlib.h>
      2 
      3 struct stacknode {
      4 	void *data;
      5 	struct stacknode *next;
      6 };
      7 
      8 struct stack {
      9 	struct stacknode *top;
     10 	size_t sz;
     11 };
     12 
     13 struct stack *
     14 stack_init(void)
     15 {
     16 	struct stack *s;
     17 
     18 	s = malloc(sizeof(*s));
     19 	if (!s)
     20 		return NULL;
     21 	s->top = NULL;
     22 	s->sz = 0;
     23 	return s;
     24 }
     25 
     26 void
     27 stack_free(struct stack *s)
     28 {
     29 	struct stacknode *n, *tmp;
     30 
     31 	n = s->top;
     32 	while (n) {
     33 		tmp = n->next;
     34 		free(tmp);
     35 		n = tmp;
     36 	}
     37 	free(s);
     38 }
     39 
     40 void *
     41 stack_push(struct stack *s, void *data)
     42 {
     43 	struct stacknode *n;
     44 
     45 	n = malloc(sizeof(*n));
     46 	if (!n)
     47 		return NULL;
     48 	n->data = data;
     49 	n->next = s->top;
     50 	s->top = n;
     51 	s->sz++;
     52 	return data;
     53 }
     54 
     55 void *
     56 stack_pop(struct stack *s)
     57 {
     58 	void *data;
     59 
     60 	if (!s->top)
     61 		return NULL;
     62 	data = s->top->data;
     63 	s->top = s->top->next;
     64 	s->sz--;
     65 	return data;
     66 }
     67 
     68 void *
     69 stack_peek(struct stack *s)
     70 {
     71 	if (!s->top)
     72 		return NULL;
     73 	return s->top->data;
     74 }
     75 
     76 size_t
     77 stack_size(struct stack *s)
     78 {
     79 	return s->sz;
     80 }