1 // LinkedList example
   2 #include <stdlib.h>
   3 #include <string.h>
   4 
   5 #include "LinkedList.h"
   6 
   7 void list_init(List *list, void (*destroy)(void *data)) {
   8     list->size = 0;
   9     list->destroy = destroy;
  10     list->head = NULL;
  11     list->tail = NULL;
  12     return;
  13 }
  14 
  15 void list_destroy(List *list) {
  16     void *data;
  17     while(list_size(list) > 0) {
  18         if(list_rem_next(list, NULL, (void **)&data) == 0 && 
  19                 list->destroy != NULL) {
  20             list->destroy(data);
  21         }
  22     }
  23     memset(list, 0, sizeof(List));
  24     return;
  25 }
  26 
  27 int list_ins_next(List *list, ListElmt *element, const void *data) {
  28     ListElmt *new_element;
  29     if((new_element=(ListElmt *)malloc(sizeof(ListElmt))) == NULL)
  30         return -1;
  31     new_element->data = (void *)data;
  32     if(element == NULL) {
  33         // insert in head of list
  34         if(list_size(list) == 0)
  35             list->tail = new_element;
  36         new_element->next = list->head;
  37         list->head = new_element;
  38     } else {
  39         // insert in not head
  40         if(element->next == NULL)
  41             list->tail = new_element;
  42         new_element->next = element->next;
  43         element->next = new_element;
  44     }
  45     list->size++;
  46     return 0;
  47 }
  48 
  49 int list_rem_next(List *list, ListElmt *element, void **data) {
  50     ListElmt *old_element;
  51     if(list_size(list) == 0) 
  52         return -1;
  53     if(element == NULL) {
  54         *data = list->head->data;
  55         old_element = list->head;
  56         list->head =list->head->next;
  57         if(list_size(list) == 1)
  58             list->tail = NULL;
  59     } else {
  60         if(element->next == NULL)
  61             return -1;
  62         *data = element->next->data;
  63         old_element = element->next;
  64         element->next = element->next->next;
  65         if(element->next == NULL)
  66             list->tail = element;
  67     }
  68     free(old_element);
  69     list->size--;
  70     return 0;
  71 }
web biohackers.net