// Implementation of the hash table module #include #include #include #include #include #include "HashTable.h" #define INITIAL_NUM_SLOTS 10 #define MAX_LOAD_FACTOR 1.0 struct hashTable { struct node **slots; int numSlots; int numItems; }; struct node { int key; int value; struct node *next; }; static void freeList(struct node *list); static inline unsigned int __unused hash(int key, int N); static void resize(HashTable ht); HashTable HashTableNew(void) { HashTable ht = malloc(sizeof(*ht)); if (ht == NULL) { fprintf(stderr, "error: out of memory\n"); exit(EXIT_FAILURE); } ht->slots = calloc(INITIAL_NUM_SLOTS, sizeof(struct node *)); if (ht->slots == NULL) { fprintf(stderr, "error: out of memory\n"); exit(EXIT_FAILURE); } ht->numSlots = INITIAL_NUM_SLOTS; ht->numItems = 0; return ht; } void HashTableFree(HashTable ht) { for (int i = 0; i < ht->numSlots; i++) { freeList(ht->slots[i]); } free(ht->slots); free(ht); } static void freeList(struct node *list) { struct node *curr = list; while (curr != NULL) { struct node *temp = curr; curr = curr->next; free(temp); } } void HashTableInsert(HashTable ht, int key, int value) { if (ht->numItems >= MAX_LOAD_FACTOR * ht->numSlots) { resize(ht); } // TODO } void HashTableDelete(HashTable ht, int key) { // TODO } bool HashTableContains(HashTable ht, int key) { // TODO return false; } int HashTableGet(HashTable ht, int key) { // TODO return -1; } int HashTableSize(HashTable ht) { // TODO return 0; } void HashTableShow(HashTable ht) { printf("%-5s %s\n", "index", "items"); for (int i = 0; i < ht->numSlots; i++) { printf("%-5d ", i); struct node *curr = ht->slots[i]; if (curr == NULL) { printf("---"); } else { while (curr != NULL) { printf("(%d, %d)", curr->key, curr->value); if (curr->next != NULL) { printf(", "); } curr = curr->next; } } printf("\n"); } } static inline unsigned int hash(int key, int N) { return key % N; } static void resize(HashTable ht) { int oldNumSlots = ht->numSlots; struct node **oldSlots = ht->slots; ht->numItems = 0; ht->numSlots *= 2; ht->slots = calloc(ht->numSlots, sizeof(struct node *)); if (ht->slots == NULL) { fprintf(stderr, "error: out of memory\n"); exit(EXIT_FAILURE); } for (int i = 0; i < oldNumSlots; i++) { struct node *curr = oldSlots[i]; while (curr != NULL) { HashTableInsert(ht, curr->key, curr->value); struct node *temp = curr; curr = curr->next; free(temp); } } free(oldSlots); }