Complete the code to declare the size of the hash map array.
const int TABLE_SIZE = [1];The hash map array size is set to 10 to allow storing multiple entries with some space.
Complete the code to compute the hash index for a given key.
unsigned int hash(char *key) {
unsigned int hash = 0;
for (int i = 0; key[i] != '\0'; i++) {
hash += key[i];
}
return hash [1] TABLE_SIZE;
}The modulo operator (%) is used to keep the hash value within the table size range.
Fix the error in the insert function to correctly add a new key-value pair.
void insert(HashMap *map, char *key, int value) {
unsigned int index = hash(key);
Entry *new_entry = malloc(sizeof(Entry));
new_entry->key = key;
new_entry->value = value;
new_entry->next = map->table[[1]];
map->table[index] = new_entry;
}The new entry's next pointer should point to the current head at the computed index, so use 'index' to access the correct bucket.
Fill both blanks to complete the search function that finds a value by key.
int search(HashMap *map, char *key) {
unsigned int index = hash(key);
Entry *current = map->table[[1]];
while (current != NULL) {
if (strcmp(current->key, [2]) == 0) {
return current->value;
}
current = current->next;
}
return -1;
}The search starts at the bucket at 'index' and compares each entry's key with the given 'key'.
Fill all three blanks to complete the delete function that removes a key from the map.
void delete(HashMap *map, char *key) {
unsigned int index = hash(key);
Entry *current = map->table[index];
Entry *prev = NULL;
while (current != NULL) {
if (strcmp(current->key, [1]) == 0) {
if ([2] == NULL) {
map->table[index] = current->next;
} else {
[3]->next = current->next;
}
free(current);
return;
}
prev = current;
current = current->next;
}
}The function compares keys, checks if the previous entry is NULL to update the head, otherwise links previous to next.
