#include #include #include typedef struct list_entry list_entry_t; struct list_entry { void *key; void *value; list_entry_t *next; }; typedef struct{ list_entry_t *list; int (*cmp)(const void *, const void *); /*Comparison function */ } list_head_t; list_head_t *list_init(int (*cmp)(const void *, const void *)){ assert(cmp!=NULL); //Create the head list_head_t *newList; //Allocate the list newList = (list_head_t *) malloc(sizeof(list_head_t)); if (newList == NULL) { fprintf(stderr, "Cannot allocate list head\n"); exit(EXIT_FAILURE); } //Assign comparison function newList->cmp=cmp; //Return the list head return newList; } list_entry_t *list_insert(list_head_t *head, void *key, void *value) { assert(head!=NULL&&key!=NULL); //Create the list entry list_entry_t *entry; //Allocate the list entry entry = (list_entry_t *) malloc(sizeof(list_entry_t)); if(entry == NULL) { return NULL; } //Assign values entry->key=key; entry->value=value; entry->next=head->list; //Move the head pointer head->list=entry; return entry; } list_entry_t *list_search_entry(list_head_t *head, void *key) { assert(head!=NULL&&key!=NULL); //Create a list entry to store temp values in list_entry_t* test; //Start with first element after head test=head->list; //Loop until end of list while(test!=NULL){ //If key matches, return value if(head->cmp(key,test->key)==0) return test; test=test->next; } return NULL; } void *list_search(list_head_t *head, void *key) { assert(head!=NULL&&key!=NULL); //Create a list entry to store temp values in list_entry_t* test; //Start with first element after head test=head->list; //Loop until end of list while(test!=NULL){ //If key matches, return value if(head->cmp(key,test->key)==0) return test->value; test=test->next; } return NULL; }