在C語言中,可以使用結構體和指針來實現hash表的設計。以下是一個簡單的hash表結構設計示例:
#define SIZE 100
typedef 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表進行操作。