帮我写一个C语言的哈希表
时间: 2023-02-07 13:47:37 浏览: 102
好的,我会尽力帮助你。
哈希表是一种常用的数据结构,它允许你在常数时间内插入、查找和删除数据。它的原理是,通过哈希函数将数据映射到表中的桶里。
以下是一个示例的 C 语言哈希表的实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASH_SIZE 10
typedef struct _hash_item {
char *key;
char *value;
struct _hash_item *next;
} hash_item;
typedef struct _hash_table {
hash_item *items[HASH_SIZE];
} hash_table;
// 哈希函数,用于将键映射到表中的桶
unsigned long hash(char *str) {
unsigned long hash = 5381;
int c;
while ((c = *str++)) {
hash = ((hash << 5) + hash) + c;
}
return hash % HASH_SIZE;
}
// 初始化哈希表
void hash_table_init(hash_table *ht) {
int i;
for (i = 0; i < HASH_SIZE; i++) {
ht->items[i] = NULL;
}
}
// 向哈希表中插入一个项
void hash_table_insert(hash_table *ht, char *key, char *value) {
unsigned long index = hash(key);
hash_item *item = malloc(sizeof(hash_item));
item->key = strdup(key);
item->value = strdup(value);
item->next = ht->items[index];
ht->items[index] = item;
}
// 从哈希表中查找一个项
char *hash_table_lookup(hash_table *ht, char *key) {
unsigned long index = hash(key);
hash_item *item = ht->items[index];
while (item) {
if (strcmp(item->key, key) == 0) {
return item->value;
}
item = item->next;
}
return NULL;
}
// 从哈希表中删除一个项
void hash_table_delete(hash_table *ht, char *key) {
unsigned long index =