HASH TABLE
Publicado por Imanol (36 intervenciones) el 02/04/2001 11:38:33
Como se utiliza una hash table en C/VBisual C.
Valora esta pregunta


0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include <limits.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <float.h>
#include <iso646.h>
#include <locale.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#include <wctype.h>
#define TABLE_SIZE 100
typedef struct {
char* key;
int value;
} Entry;
typedef struct {
Entry* entries[TABLE_SIZE];
} HashTable;
unsigned int hash(const char* key) {
unsigned int hash = 0;
for (int i = 0; key != '\0'; i++) {
hash = (hash * 31) + key;
}
return hash % TABLE_SIZE;
}
HashTable* createHashTable() {
HashTable* hashtable = malloc(sizeof(HashTable));
memset(hashtable->entries, 0, sizeof(Entry*) * TABLE_SIZE);
return hashtable;
}
void insert(HashTable* hashtable, const char* key, int value) {
unsigned int index = hash(key);
Entry* entry = malloc(sizeof(Entry));
entry->key = strdup(key);
entry->value = value;
hashtable->entries[index] = entry;
}
int get(HashTable* hashtable, const char* key) {
unsigned int index = hash(key);
Entry* entry = hashtable->entries[index];
if (entry != NULL && strcmp(entry->key, key) == 0) {
return entry->value;
}
return -1; // Valor predeterminado si no se encuentra la clave
}
void removeEntry(HashTable* hashtable, const char* key) {
unsigned int index = hash(key);
Entry* entry = hashtable->entries[index];
if (entry != NULL && strcmp(entry->key, key) == 0) {
free(entry->key);
free(entry);
hashtable->entries[index] = NULL;
}
}
void destroyHashTable(HashTable* hashtable) {
for (int i = 0; i < TABLE_SIZE; i++) {
Entry* entry = hashtable->entries;
if (entry != NULL) {
free(entry->key);
free(entry);
}
}
free(hashtable);
}
int main() {
HashTable* hashtable = createHashTable();
insert(hashtable, "clave1", 10);
insert(hashtable, "clave2", 20);
int valor1 = get(hashtable, "clave1");
int valor2 = get(hashtable, "clave2");
printf("Valor1: %d\n", valor1);
printf("Valor2: %d\n", valor2);
removeEntry(hashtable, "clave1");
int valor1_actualizado = get(hashtable, "clave1");
printf("Valor1 actualizado: %d\n", valor1_actualizado);
destroyHashTable(hashtable);
return 0;
}