How is the hash function used in the C programming language?

A hash function in the C language can be used to generate a hash value for data, mapping the input data to a unique identifier of fixed length. Here is a simple example:

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

The code above demonstrates a basic hash table, using a simple hash function to map string keys to hash values, and storing key-value pairs in the hash table. You can modify the hash function and the size of the hash table according to your specific needs to accommodate different situations.

bannerAds