在C语言中,可以使用结构体和指针来实现hash表的设计。以下是一个简单的hash表结构设计示例:
#define SIZE 100typedef struct Node { int key; int value; struct Node* next;} Node;typedef struct HashTable { Node* table[SIZE];} HashTable;// 初始化hash表void initHashTable(HashTable* ht) { for (int i = 0; i < SIZE; i++) { ht->table[i] = NULL; }}// 哈希函数,将key映射到数组索引int hashFunction(int key) { return key % SIZE;}// 插入键值对void insert(HashTable* ht, int key, int value) { int index = hashFunction(key); Node* newNode = (Node*)malloc(sizeof(Node)); newNode->key = key; newNode->value = value; newNode->next = NULL; if (ht->table[index] == NULL) { ht->table[index] = newNode; } else { Node* current = ht->table[index]; while (current->next != NULL) { current = current->next; } current->next = newNode; }}// 查找键对应的值int find(HashTable* ht, int key) { int index = hashFunction(key); Node* current = ht->table[index]; while (current != NULL) { if (current->key == key) { return current->value; } current = current->next; } return -1; // 表示未找到}以上示例中,我们定义了一个Node结构体用来存储键值对,以及一个HashTable结构体用来存储hash表。在HashTable结构体中,使用一个指针数组来表示hash表的存储空间。
我们还定义了一些操作函数,如initHashTable用来初始化hash表,hashFunction用来计算key的哈希值,insert用来插入键值对,find用来查找键对应的值。通过这些操作函数,可以方便地对hash表进行操作。