Hashmap gerado pelo chat GPT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 1000
// Definição da estrutura do elemento da tabela hash
typedef struct Element {
char* key;
int value;
struct Element* next;
} Element;
// Definição da estrutura da tabela hash
typedef struct HashTable {
Element** buckets;
} HashTable;
// Função hash simples que retorna um índice a partir da chave
unsigned int hash(char* key) {
unsigned int hashval = 0;
for (; *key != '\0'; key++) {
hashval = *key + 31 * hashval;
}
return hashval % TABLE_SIZE;
}
// Função que cria e retorna um novo elemento
Element* new_element(char* key, int value) {
Element* elem = (Element*)malloc(sizeof(Element));
elem->key = key;
elem->value = value;
elem->next = NULL;
return elem;
}
// Função que cria e retorna uma nova tabela hash
HashTable* new_hash_table() {
HashTable* table = (HashTable*)malloc(sizeof(HashTable));
table->buckets = (Element**)calloc(TABLE_SIZE, sizeof(Element*));
return table;
}
// Função que insere um elemento na tabela hash
void insert(HashTable* table, char* key, int value) {
unsigned int index = hash(key);
Element* elem = new_element(key, value);
elem->next = table->buckets[index];
table->buckets[index] = elem;
}
// Função que busca e retorna o valor associado à chave na tabela hash
int search(HashTable* table, char* key) {
unsigned int index = hash(key);
Element* elem = table->buckets[index];
while (elem != NULL) {
if (strcmp(elem->key, key) == 0) {
return elem->value;
}
elem = elem->next;
}
return -1;
}
// Função que remove um elemento da tabela hash
void remove_element(HashTable* table, char* key) {
unsigned int index = hash(key);
Element* elem = table->buckets[index];
Element* prev = NULL;
while (elem != NULL) {
if (strcmp(elem->key, key) == 0) {
if (prev == NULL) {
table->buckets[index] = elem->next;
}
else {
prev->next = elem->next;
}
free(elem);
return;
}
prev = elem;
elem = elem->next;
}
}
// Função que imprime os elementos da tabela hash
void print_table(HashTable* table) {
for (int i = 0; i < TABLE_SIZE; i++) {
Element* elem = table->buckets[i];
while (elem != NULL) {
printf("Key: %s, Value: %d\n", elem->key, elem->value);
elem = elem->next;
}
}
}
// Função principal
int main()
{
HashTable* table = new_hash_table();
// Exemplo de inserção de elementos
insert(table, "key1", 1);
insert(table, "key2", 2);
}
Neste código , inserindo duas vezes com a mesma chave gera um leak.