graph

unidirected graph implementation using adjacency list
Index Commits Files Refs README LICENSE
stack.c (1054B)
   1 /* Stack implementation using a vector to store the elements */
   2 
   3 #include "stack.h"
   4 
   5 #include <stdio.h>
   6 #include <string.h>
   7 
   8 void stack_new(Stack **S, size_t mem_width) {
   9     (*S) = malloc(sizeof(Stack));
  10     (*S)->vector = malloc(sizeof(Stack *) * STACK_INITIAL_ALLOC);
  11     (*S)->mem_width = mem_width;
  12     (*S)->mem_alloc = STACK_INITIAL_ALLOC;
  13     (*S)->len = 0;
  14 }
  15 
  16 /* generates a copy of the element an push it into stack
  17  * does not check if elem is valid type */
  18 void stack_push(Stack *S, const void *elem) {
  19     if(S->mem_alloc == S->len)
  20         S->vector = realloc(S->vector, 
  21                 (S->mem_alloc *= STACK_GROWTH_FACTOR) * sizeof(Stack *));
  22 
  23     S->vector[S->len] = malloc(S->mem_width);
  24     memcpy(S->vector[S->len++], elem, S->mem_width);
  25 }
  26 
  27 void stack_peek(const Stack *S, void *data) {
  28     data = S->len ? S->vector[S->len - 1] : NULL;
  29 }
  30 
  31 void stack_pop(Stack *S, void *data) {
  32     memcpy(data, S->vector[--S->len], S->mem_width);
  33     free(S->vector[S->len]);
  34 }
  35 
  36 bool stack_is_empty(const Stack *S) {
  37     return S->len;
  38 }
  39 
  40 void stack_destroy(Stack *S) {
  41     free(S->vector);
  42     free(S);
  43 }
  44