Implement an hash table in C
- User
Implement an hash table in C
Assistant
Sure, here's an example implementation of a hash table in C:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_TABLE_SIZE 1024 typedef struct hash_table { int size; int (*hash)(const void *key); void *data[MAX_TABLE_SIZE]; } hash_table; int hash(const void *key) { return (int)key % MAX_TABLE_SIZE; } void init_hash_table(hash_table *table) { table->size = 0; table->hash = hash; memset(table->data, 0, sizeof(void *) * MAX_TABLE_SIZE); } void insert_hash_table(hash_table *table, const void *key, void *value) { int index = table->hash(key) % MAX_TABLE_SIZE; if (table->data[index] == NULL) { table->data[index] = value; table->size++; } else { printf("Error: key already exists in table\n"); } } void *lookup_hash_table(hash_table *table, const void *key) { int index = table->hash(key) % MAX_TABLE_SIZE; if (table->data[index] != NULL) { return table->data[index]; } else { return NULL; } } void delete_hash_table(hash_table *table, const void *key) { int index = table->hash(key) % MAX_TABLE_SIZE; if (table->data[index] != NULL) { table->data[index] = NULL; table->size--; } else { printf("Error: key does not exist in table\n"); } } int main() { hash_table table; init_hash_table(&table); insert_hash_table(&table, "apple", "red"); insert_hash_table(&table, "banana
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.