用c++不依赖原有的哈希库创建一个哈希表,包括添加,查找,删除操作
时间: 2023-05-11 17:05:00 浏览: 98
好的,以下是一个简单的用 C 语言实现的哈希表,包括添加、查找和删除操作的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct {
char* key;
char* value;
} Entry;
typedef struct {
Entry* entries[TABLE_SIZE];
} HashTable;
unsigned int hash(const char* key) {
unsigned int hash = 0;
for (int i = 0; i < strlen(key); i++) {
hash = hash * 31 + key[i];
}
return hash % TABLE_SIZE;
}
void insert(HashTable* table, const char* key, const char* value) {
unsigned int index = hash(key);
Entry* entry = malloc(sizeof(Entry));
entry->key = strdup(key);
entry->value = strdup(value);
table->entries[index] = entry;
}
char* lookup(HashTable* table, const char* key) {
unsigned int index = hash(key);
if (table->entries[index] != NULL) {
return table->entries[index]->value;
} else {
return NULL;
}
}
void delete(HashTable* table, const char* key) {
unsigned int index = hash(key);
if (table->entries[index] != NULL) {
free(table->entries[index]->key);
free(table->entries[index]->value);
free(table->entries[index]);
table->entries[index] = NULL;
}
}
int main() {
HashTable table;
insert(&table, "apple", "a fruit");
insert(&table, "banana", "another fruit");
printf("%s\n", lookup(&table, "apple"));
delete(&table, "apple");
printf("%s\n", lookup(&table, "apple"));
return 0;
}
```
这个哈希表使用了一个简单的哈希函数,将字符串的每个字符的 ASCII 码相加并乘以一个常数 31,最后取余数得到哈希值。然后,使用这个哈希值作为数组的下标,将键值对存储在哈希表中。添加、查找和删除操作都是基于这个哈希值进行的。
阅读全文