首先,我们需要定义我们的数据结构。在这个例子中,我们将创建一个结构体来存储姓名和电话号码。然后,我们将使用一个哈希表来存储这些结构体的指针。哈希表本身只是一个整数数组,其索引由电话号码的哈希值决定。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// 定义我们的数据结构来存储姓名和电话号码
typedef struct Contact {
char name[100];
char phoneNumber[20]; // 假设电话号码不会超过这个长度
} Contact;
// 定义哈希表的大小
#define HASH_SIZE 100003 // 选择一个质数作为哈希表的大小
Contact* hashTable[HASH_SIZE]; // 我们的哈希表,存储Contact结构体的指针
// 计算电话号码的哈希值
unsigned int hash(const char* phoneNumber) {
unsigned int hashValue = 0;
while (*phoneNumber) {
hashValue = (hashValue << 5) + *phoneNumber++; // 使用简单的哈希函数,实际应用中可能需要更复杂的哈希函数
}
return hashValue % HASH_SIZE; // 对哈希表大小取模,得到在哈希表中的位置
}
// 添加一个新的电话号码到哈希表中
void addContact(const char* name, const char* phoneNumber) {
unsigned int index = hash(phoneNumber); // 计算电话号码的哈希值
Contact* newContact = (Contact*)malloc(sizeof(Contact)); // 创建新的Contact结构体实例
strcpy(newContact->name, name); // 复制姓名到新的Contact结构体实例中
strcpy(newContact->phoneNumber, phoneNumber); // 复制电话号码到新的Contact结构体实例中
hashTable[index] = newContact; // 将新的Contact结构体实例添加到哈希表中
}
// 查询电话号码对应的姓名
const char* findContact(const char* phoneNumber) {
unsigned int index = hash(phoneNumber); // 计算电话号码的哈希值
if (hashTable[index] != NULL && strcmp(hashTable[index]->phoneNumber, phoneNumber) == 0) { // 如果找到了匹配的电话号码,返回对应的姓名
return hashTable[index]->name;
} else { // 如果没找到匹配的电话号码,返回空字符串表示没有找到对应的姓名
return "";
}
}这个程序没有处理哈希冲突的情况,在实际应用中,如果两个不同的电话号码产生了相同的哈希值(即两个不同的键产生了相同的索引),我们需要使用一种方法来处理这种情况,例如开放地址法(Open Addressing)或链表法(Chaining),这个程序也没有处理动态内存释放的问题,在实际应用中,你需要确保正确地管理内存,避免内存泄漏等问题。





