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;
}
以上代碼實現了一個簡單的哈希表,其中使用了一個簡單的哈希函數將字符串鍵映射為哈希值,然后將鍵值對存儲在哈希表中。你可以根據實際需求修改哈希函數和哈希表的大小來適應不同的場景。