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