core/list.c

Go to the documentation of this file.
00001 
00009 #include <stdlib.h>
00010 #include <errno.h>
00011 #include "list.h"
00012 
00018 static LISTITEM *create_item(void *data,    /* a pointer to the data */
00019                              LISTITEM *prev,    /* the item preceding the new item */
00020                              LISTITEM *next)    /* the item following the new item */
00021 {
00022     LISTITEM *item = malloc(sizeof(LISTITEM));
00023     if (item!=NULL)
00024     {
00025         item->data = data;
00026         item->next = next;
00027         item->prev = prev;
00028     }
00029     else
00030         errno = ENOMEM;
00031     return item;
00032 }
00033 
00036 static void destroy_item(LISTITEM *item) 
00037 {
00038     if (item->prev!=NULL) 
00039         item->prev->next = item->next;
00040     if (item->next!=NULL) 
00041         item->next->prev = item->prev;
00042     free(item);
00043 }
00044 
00050 LIST *list_create(void)
00051 {
00052     LIST *list = malloc(sizeof(LIST));
00053     if (list!=NULL)
00054     {
00055         list->first = NULL;
00056         list->last = NULL;
00057         list->size = 0;
00058     }
00059     else
00060         errno = ENOMEM;
00061     return list;
00062 }
00063 
00066 void list_destroy(LIST *list) 
00067 {
00068     LISTITEM *item;
00069     for (item=list->first; item!=NULL; item=item->next)
00070     {
00071         destroy_item(item);
00072         list->size--;
00073     }
00074     /* list size should be zero here */
00075 }
00076 
00082 LISTITEM *list_append(LIST *list, 
00083                       void *data) 
00084 {
00085     LISTITEM *item = create_item(data,list->last,NULL);
00086     if (item!=NULL) {
00087         if (list->first==NULL)
00088             list->first = item;
00089         if (list->last!=NULL)
00090             list->last->next = item;
00091         list->last = item;
00092         list->size++;
00093     }
00094     return item;
00095 }
00096 
00099 void list_shuffle(LIST *list)
00100 {
00101     LISTITEM **index;
00102     unsigned int i=0;
00103     LISTITEM *item;
00104 
00105     if (list == NULL)
00106         return;
00107     if (list->size < 2)
00108         return;
00109 
00110     index = (LISTITEM**)malloc(sizeof(LISTITEM*)*list->size);
00111     for (item=list->first; item!=NULL; item=item->next)
00112         index[i++] = item;
00113     for (i=0; i<list->size; i++)
00114     {
00115         LISTITEM *from = index[i], *to;
00116         unsigned int j = rand() % list->size;
00117         void *temp = from->data;
00118         to = index[j];
00119         from->data = to->data;
00120         to->data = temp;
00121     }
00122     free(index);
00123 }

GridLAB-DTM Version 1.0
An open-source project initiated by the US Department of Energy