C言語でのハッシュ関数の使い方を教えてください。

Cのハッシュ関数は、データのハッシュ値を生成するために使用され、入力されたデータを固定長のユニークな識別子にマッピングします。以下は簡単な例です:

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

上記のコードは、単純なハッシュテーブルを実装しており、文字列キーをハッシュ値にマッピングし、キーと値のペアをハッシュテーブルに格納しています。実際のニーズに応じて、ハッシュ関数やハッシュテーブルのサイズを変更して、さまざまなシーンに適応させることができます。

bannerAds