lista_dinamica.c (2744B)
1 #include <stdlib.h> 2 #include "lista_dinamica.h" 3 4 5 dynamic_list_T* init_dynamic_list(size_t item_size){ 6 dynamic_list_T* list = calloc(1, sizeof(dynamic_list_T)); 7 list->item_size = item_size; 8 list->length = 0; 9 list->items = (void*) 0; 10 11 return list; 12 } 13 14 15 // Devolve o indice dun elemento se esta na lista e -1 senon esta na lista 16 int dynamic_list_find(dynamic_list_T* dynamic_list, void* item, int (*equals_method)(void* x, void* y)){ 17 for(int i = 0; i < dynamic_list->length; i++){ 18 if(equals_method(dynamic_list->items[i], item)){ 19 return i; 20 } 21 } 22 return -1; 23 } 24 25 26 void dynamic_list_append(dynamic_list_T* dynamic_list, void* item){ 27 dynamic_list->length += 1; 28 if (dynamic_list->items == (void*) 0){ // Se a lista esta baleira reserva memoria para un so elemento 29 dynamic_list->items = calloc(1, dynamic_list->item_size); 30 } else{ 31 // re-estructura a memoria reservada (numero de elementos * tamanho do elemento) 32 dynamic_list->items = realloc(dynamic_list->items, dynamic_list->length * dynamic_list->item_size); 33 } 34 dynamic_list->items[dynamic_list->length-1] = item; 35 } 36 37 38 39 void dynamic_list_shift_left(dynamic_list_T* dynamic_list, int index){ 40 for(int i = index; i < dynamic_list->length-1; i++){ 41 dynamic_list->items[i] = dynamic_list->items[i+1]; 42 } 43 } 44 45 46 47 int dynamic_list_delete(dynamic_list_T* dynamic_list, int index){ 48 if(dynamic_list->length > index){ 49 dynamic_list_shift_left(dynamic_list, index); 50 dynamic_list->length -= 1; 51 dynamic_list->items = realloc(dynamic_list->items, dynamic_list->length * dynamic_list->item_size); 52 return 1; 53 } 54 return 0; 55 } 56 57 58 59 // Comprobar se o obxeto esta na lista e devolver 1 se esta e foi borrado ou 0 se non esta 60 int dynamic_list_remove(dynamic_list_T* dynamic_list, void* item, void (*free_method)(void* x)){ 61 for(int i = 0; i < dynamic_list->length; i++){ 62 // Se atopas o item na lista borralo 63 if( dynamic_list->items[i] == item ){ 64 if (free_method) free_method(item); // Libera memoria do item que se pasa x parametro 65 dynamic_list_shift_left(dynamic_list, i); 66 dynamic_list->length -= 1; 67 dynamic_list->items = realloc(dynamic_list->items, dynamic_list->length * dynamic_list->item_size); 68 return 1; 69 } 70 } 71 return 0; 72 } 73 74 void* dynamic_list_get(dynamic_list_T* dynamic_list, int idx){ 75 return dynamic_list->items[idx]; 76 } 77 78 79 void dynamic_list_free(dynamic_list_T* dynamic_list, void(*free_method)(void* x)){ 80 for(int i = 0; i < dynamic_list->length; i++){ 81 free_method(dynamic_list->items[i]); 82 } 83 84 free(dynamic_list->items); 85 free(dynamic_list); 86 87 } 88