c++实现不用类的用拉链法的哈希表
时间: 2023-05-26 17:02:51 浏览: 62
以下是一个不用类的用拉链法实现哈希表的示例代码:
```c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 100
// 哈希表节点
typedef struct Node {
char* key;
char* value;
struct Node* next;
} Node;
// 哈希表
typedef struct HashTable {
Node** table;
} HashTable;
// 哈希函数
int hash(char* key) {
int hash = 0;
int i = 0;
int len = strlen(key);
for (i = 0; i < len; i++) {
hash += key[i];
}
return hash % MAX_SIZE;
}
// 创建一个哈希表节点
Node* create_node(char* key, char* value) {
Node* node = (Node*)malloc(sizeof(Node));
node->key = (char*)malloc(sizeof(key));
node->value = (char*)malloc(sizeof(value));
strcpy(node->key, key);
strcpy(node->value, value);
node->next = NULL;
return node;
}
// 插入一个键值对
void insert(HashTable* ht, char* key, char* value) {
int index = hash(key);
if (ht->table[index] == NULL) {
ht->table[index] = create_node(key, value);
} else {
Node* curr = ht->table[index];
while (curr->next != NULL) {
if (strcmp(curr->key, key) == 0) {
curr->value = value;
return;
}
curr = curr->next;
}
if (strcmp(curr->key, key) == 0) {
curr->value = value;
} else {
curr->next = create_node(key, value);
}
}
}
// 查找一个键对应的值
char* find(HashTable* ht, char* key) {
int index = hash(key);
Node* curr = ht->table[index];
while (curr != NULL) {
if (strcmp(curr->key, key) == 0) {
return curr->value;
}
curr = curr->next;
}
return NULL;
}
// 创建一个哈希表
HashTable* create_hashtable() {
HashTable* ht = (HashTable*)malloc(sizeof(HashTable));
ht->table = (Node**)malloc(sizeof(Node*) * MAX_SIZE);
int i;
for (i = 0; i < MAX_SIZE; i++) {
ht->table[i] = NULL;
}
return ht;
}
// 销毁一个哈希表
void destroy_hashtable(HashTable* ht) {
int i;
for (i = 0; i < MAX_SIZE; i++) {
Node* curr = ht->table[i];
while (curr != NULL) {
Node* next = curr->next;
free(curr->key);
free(curr->value);
free(curr);
curr = next;
}
}
free(ht->table);
free(ht);
}
int main() {
HashTable* ht = create_hashtable();
insert(ht, "name", "Tom");
insert(ht, "age", "20");
insert(ht, "phone", "123456");
printf("%s\n", find(ht, "name"));
printf("%s\n", find(ht, "age"));
printf("%s\n", find(ht, "phone"));
destroy_hashtable(ht);
return 0;
}
```
以上代码实现了一个基本的不用类的用拉链法实现哈希表,并提供了插入、查找和销毁哈希表的函数。可以按照自己的需求进行修改和扩展。