利用hash,实现电子辞典

因为哈希表提供了快速的查找和插入操作。单词查找起来更高效!

然而,如何使用哈希表来实现电子词典呢?直接上代码

#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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值