graph

unidirected graph implementation using adjacency list
Index Commits Files Refs README LICENSE
queue.c (1133B)
   1 #include "queue.h"
   2 
   3 /* FIFO: First In First Out */
   4 
   5 #include <stdio.h>
   6 #include <stdlib.h>
   7 #include <string.h>
   8 #include <assert.h>
   9 
  10 void queue_new(Queue **Q, size_t type_size) {
  11     (*Q) = malloc(sizeof(Queue));
  12     (*Q)->first = NULL;
  13     (*Q)->end = NULL;
  14     (*Q)->type_size = type_size;
  15 }
  16 
  17 void queue_enqueue(Queue *Q, void *data) {
  18     Node *new = malloc(sizeof(Node));
  19     new->data = malloc(Q->type_size);
  20     memcpy(new->data, data, Q->type_size);
  21 
  22     if(!Q->first) Q->first = new;
  23 
  24     if(!Q->end) Q->end = new;
  25     else Q->end->next = new;
  26 
  27     new->prev = Q->end;
  28     new->next = NULL;
  29     Q->end = new;
  30 }
  31 
  32 void queue_dequeue(Queue *Q, void *data) {
  33     assert(Q->first);
  34     assert(Q->end);
  35 
  36     memcpy(data, Q->first->data, Q->type_size);
  37 
  38     Q->first->prev = Q->first;
  39     Q->first = Q->first->next;
  40     if(Q->first == NULL) return;
  41 
  42     free(Q->first->prev->data);
  43     free(Q->first->prev);
  44     Q->first->prev = NULL;
  45 }
  46 
  47 bool queue_is_empty(Queue *Q) {
  48     return Q->first;
  49 }
  50 
  51 void queue_destroy(Queue *Q) {
  52     for(Node *n = Q->first; n; n = n->next)
  53         free(n->prev);
  54 
  55     if(Q->end)
  56         free(Q->end->data);
  57 
  58     free(Q->end);
  59     if(Q->first)
  60         free(Q->first->data);
  61 
  62     free(Q->first);
  63     free(Q);
  64 }