以下是一个简单的哈希表实现示例,使用了开放地址法中的线性探测再散列技术:
#include <stdlib.h>
#include <string.h>
#define HASH_TABLE_SIZE 256
typedef struct HashNode {
char *key;
char *value;
struct HashNode *next;
} HashNode;
typedef struct HashTable {
HashNode *nodes[HASH_TABLE_SIZE];
} HashTable;
unsigned int hash(const char *key) {
unsigned int hash_value = 0;
while (*key) {
hash_value = (hash_value << 5) - hash_value + (unsigned char)(*key++);
}
return hash_value % HASH_TABLE_SIZE;
}
HashTable *create_hash_table() {
HashTable *table = (HashTable *)malloc(sizeof(HashTable));
if (table == NULL) {
return NULL;
}
memset(table, 0, sizeof(HashTable));
return table;
}
int hash_table_insert(HashTable *table, const char *key, const char *value) {
if (table == NULL || key == NULL || value == NULL) {
return -1;
}
unsigned int key_hash = hash(key);
HashNode *node = table->nodes[key_hash];
while (node != NULL && strcmp(node->key, key) != 0) {
node = node->next;
}
if (node == NULL) {
node = (HashNode *)malloc(sizeof(HashNode));
if (node == NULL) {
return -1;
}
node->key = strdup(key);
node->value = strdup(value);
node->next = table->nodes[key_hash];
table->nodes[key_hash] = node;
} else {
free(node->value);
node->value = strdup(value);
}
return 0;
}
char *hash_table_search(HashTable *table, const char *key) {
if (table == NULL || key == NULL) {
return NULL;
}
unsigned int key_hash = hash(key);
HashNode *node = table->nodes[key_hash];
while (node != NULL && strcmp(node->key, key) != 0) {
node = node->next;
}
return node ? node->value : NULL;
}
// 示例用法
int main() {
HashTable *table = create_hash_table();
if (table == NULL) {
return -1;
}
hash_table_insert(table, "name", "John");
hash_table_insert(table, "age", "30");
hash_table_insert(table, "city", "New York");
char *value = hash_table_search(table, "name");
if (value) {