c语言hash函数如何用

   2025-02-05 8620
核心提示:C语言中的Hash函数可以用于生成一个数据的哈希值,将输入的数据映射为一个固定长度的唯一标识符。下面是一个简单的例子:#includ

C语言中的Hash函数可以用于生成一个数据的哈希值,将输入的数据映射为一个固定长度的唯一标识符。下面是一个简单的例子:

#include <stdio.h>#include <string.h>#define HASH_TABLE_SIZE 100// 定义哈希表节点结构typedef struct hash_node {    char key[50];    int value;    struct hash_node* next;} HashNode;// 定义哈希表结构typedef struct hash_table {    HashNode* nodes[HASH_TABLE_SIZE];} HashTable;// 创建哈希表HashTable* createHashTable() {    HashTable* hashTable = (HashTable*)malloc(sizeof(HashTable));    memset(hashTable->nodes, 0, sizeof(HashNode*) * HASH_TABLE_SIZE);    return hashTable;}// 哈希函数unsigned int hash(char* key) {    unsigned int hashValue = 0;    int i = 0;    while (key[i] != '\0') {        hashValue = (hashValue << 5) + key[i++];    }    return hashValue % HASH_TABLE_SIZE;}// 插入数据到哈希表void insert(HashTable* hashTable, char* key, int value) {    unsigned int hashValue = hash(key);    HashNode* newNode = (HashNode*)malloc(sizeof(HashNode));    strcpy(newNode->key, key);    newNode->value = value;    newNode->next = NULL;    if (hashTable->nodes[hashValue] == NULL) {        hashTable->nodes[hashValue] = newNode;    } else {        HashNode* currentNode = hashTable->nodes[hashValue];        while (currentNode->next != NULL) {            currentNode = currentNode->next;        }        currentNode->next = newNode;    }}// 查找数据int find(HashTable* hashTable, char* key) {    unsigned int hashValue = hash(key);    HashNode* currentNode = hashTable->nodes[hashValue];    while (currentNode != NULL) {        if (strcmp(currentNode->key, key) == 0) {            return currentNode->value;        }        currentNode = currentNode->next;    }    return -1;}int main() {    HashTable* hashTable = createHashTable();    insert(hashTable, "apple", 5);    insert(hashTable, "banana", 8);    insert(hashTable, "orange", 12);    printf("apple: %d\n", find(hashTable, "apple"));    printf("banana: %d\n", find(hashTable, "banana"));    printf("orange: %d\n", find(hashTable, "orange"));    printf("grape: %d\n", find(hashTable, "grape"));    return 0;}

以上代码实现了一个简单的哈希表,其中使用了一个简单的哈希函数将字符串键映射为哈希值,然后将键值对存储在哈希表中。你可以根据实际需求修改哈希函数和哈希表的大小来适应不同的场景。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言