C语言实现哈希表
哈希表是一种常用的数据结构,它可以快速地进行数据的查找和插入操作。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* table[TABLE_SIZE];
};
int hash_key(char* key) {
int hash = 0;
for (int i = 0; i < strlen(key); i++) {
hash += key[i];
}
return hash % TABLE_SIZE;
}
void insert(struct hash_table* ht, char* key, char* value) {
int index = hash_key(key);
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->key = key;
new_node->value = value;
new_node->next = NULL;
if (ht->table[index] == NULL) {
ht->table[index] = new_node;
} else {
struct node* current = ht->table[index];
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}
}
char* get(struct hash_table* ht, char* key) {
int index = hash_key(key);
struct node* current = ht->table[index];
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
return current->value;
}
current = current->next;
}
return NULL;
}
int main() {
struct hash_table ht;
memset(&ht, 0, sizeof(struct hash_table));
insert(&ht, "apple", "red");
insert(&ht, "banana", "yellow");
insert(&ht, "grape", "purple");
printf("apple: %s\n", get(&ht, "apple"));
printf("banana: %s\n", get(&ht, "banana"));
printf("grape: %s\n", get(&ht, "grape"));
printf("orange: %s\n", get(&ht, "orange"));
return 0;
}
在这个实现中,我们定义了两个结构体:node和hash_table。node表示哈希表中的一个节点,它包含一个键值对和指向下一个节点的指针。hash_table表示整个哈希表,它包含一个指向node数组的指针。
hash_key函数用来计算键的哈希值。我们采用了一个简单的方法,将键的每个字符的ASCII码相加,并对数组长度取余。
insert函数用来插入一个键值对到哈希表中。如果这个键的哈希值对应的位置为空,则直接插入;否则,遍历这个位置的链表,直到找到最后一个节点,然后将新的节点插入到链表的末尾。
get函数用来根据键在哈希表中查找对应的值。首先计算键的哈希值,然后在对应位置的链表中查找,直到找到对应的键或者链表遍历完毕。
在main函数中,我们创建了一个hash_table结构体,并向其中插入了三个键值对。然后通过get函数来查找对应的值,并输出结果。
注意,在本实现中,我们没有考虑哈希冲突的情况。在实际应用中,可能会出现多个键的哈希值相同的情况,这时需要采用一些解决冲突的方法,如链地址法、开放地址法等。
原文地址: https://www.cveoy.top/t/topic/qXt 著作权归作者所有。请勿转载和采集!