因为哈希表提供了快速的查找和插入操作。单词查找起来更高效!
然而,如何使用哈希表来实现电子词典呢?直接上代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义单词和解释的结构体
typedef struct {
char word[50];
char definition[200];
} Entry;
// 定义哈希表的大小
#define TABLE_SIZE 100
// 哈希表节点的结构体
typedef struct HashNode {
Entry entry;
struct HashNode *next;
} HashNode;
// 哈希表结构体
typedef struct {
HashNode *buckets[TABLE_SIZE];
} HashMap;
// 哈希函数,计算字符串的哈希值
unsigned int hash(const char *str) {
unsigned int hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c;
return hash % TABLE_SIZE;
}
// 初始化哈希表
void initHashMap(HashMap *map) {
for (int i = 0; i < TABLE_SIZE; i++) {
map->buckets[i] = NULL;
}
}
// 向哈希表中插入一个单词和解释
void insertEntry(HashMap *map, const char *word, const char *definition) {
int index = hash(word);
HashNode *newNode = (HashNode *)malloc(sizeof(HashNode));
strcpy(newNode->entry.word, word);
strcpy(newNode->entry.definition, definition);
newNode->next = map->buckets[index];
map->buckets[index] = newNode;
}
// 查找单词对应的解释
const char *findDefinition(const HashMap *map, const char *word) {
int index = hash(word);
HashNode *node = map->buckets[index];
while (node != NULL) {
if (strcmp(node->entry.word, word) == 0) {
return node->entry.definition;
}
node = node->next;
}
return "Word not found";
}
int main() {
HashMap dictionary;
initHashMap(&dictionary);
// 插入一些单词和解释
insertEntry(&dictionary, "apple", "A fruit that grows on trees and is commonly red or green.");
insertEntry(&dictionary, "banana", "A long curved fruit that grows in clusters and has soft pulpy flesh and yellow skin when ripe.");
// 查找单词并打印解释
printf("Definition of 'apple': %s\n", findDefinition(&dictionary, "apple"));
printf("Definition of 'banana': %s\n", findDefinition(&dictionary, "banana"));
return 0;
}