使用C++写一个Hash表的实现,只需要写出代码
时间: 2023-03-20 11:00:51 浏览: 109
一个简单的hash表的构建
5星 · 资源好评率100%
抱歉,我无法提供实际的编程功能,但我可以给您提供一个基本的哈希表实现示例,如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
struct node {
char *key;
char *value;
struct node *next;
};
struct hash_table {
struct node *list[TABLE_SIZE];
};
int hash_function(char *key) {
int hash_value = 0;
for (int i = 0; i < strlen(key); i++) {
hash_value += key[i];
}
return hash_value % TABLE_SIZE;
}
struct node *create_node(char *key, char *value) {
struct node *new_node = (struct node *) malloc(sizeof(struct node));
new_node->key = (char *) malloc(strlen(key) + 1);
new_node->value = (char *) malloc(strlen(value) + 1);
strcpy(new_node->key, key);
strcpy(new_node->value, value);
new_node->next = NULL;
return new_node;
}
void insert(struct hash_table *ht, char *key, char *value) {
int index = hash_function(key);
struct node *new_node = create_node(key, value);
new_node->next = ht->list[index];
ht->list[index] = new_node;
}
char *search(struct hash_table *ht, char *key) {
int index = hash_function(key);
struct node *current_node = ht->list[index];
while (current_node != NULL) {
if (strcmp(current_node->key, key) == 0) {
return current_node->value;
}
current_node = current_node->next;
}
return NULL;
}
void delete(struct hash_table *ht, char *key) {
int index = hash_function(key);
struct node *current_node = ht->list[index];
struct node *previous_node = NULL;
while (current_node != NULL) {
if (strcmp(current_node->key, key) == 0) {
if (previous_node == NULL) {
ht->list[index] = current_node->next;
} else {
previous_node->next = current_node->next;
}
free(current_node->key);
free(current_node->value);
free(current_node);
return;
}
previous_node = current_node;
current_node = current_node->next;
}
}
int main() {
struct hash_table ht;
for (int i = 0; i < TABLE_SIZE; i++) {
ht.list[i] = NULL;
}
insert(&ht, "apple", "a sweet fruit");
insert(&ht, "banana", "a yellow fruit");
insert(&ht, "cherry", "a small red fruit");
char *value = search(&ht, "apple");
if (value == NULL) {
printf("Key not found\n");
} else {
printf("Value: %s\n", value);
}
delete(&ht, "apple");
value = search(&ht, "apple");
if (value == NULL) {
printf("Key not found\n");
} else {
printf("Value: %s\n", value);
}
return 0;
}
```
这个示例实现了一个简单的哈希表,使用了一个基本的哈希函数,一个链式散列表,以及插入,查找和删除元
阅读全文