How to create a hash table in the C language?
In C language, a hash table can be created by following these steps:
- Create a structure for a hash table with two members: a fixed-size array to store data, and a flag array to indicate whether each position in the array has data. For instance:
#define SIZE 10
typedef struct {
int data[SIZE];
int flags[SIZE];
} HashTable;
- Initialize the hash table by setting all elements in the array and flag array to their initial values (e.g. 0).
void initializeHashTable(HashTable* hashTable) {
int i;
for(i = 0; i < SIZE; i++) {
hashTable->data[i] = 0;
hashTable->flags[i] = 0;
}
}
- Implement a hash function that maps the data to be inserted to a position in the hash table. Common hash functions include division hashing, multiplication hashing, square mid-digits, and more. For example, here is a simple division hashing method:
int hashFunction(int key) {
return key % SIZE;
}
- Implement the insertion operation, inserting data into the corresponding position in the hash table. If that position already has data, use a conflict resolution strategy (such as linear probing, quadratic probing, separate chaining, etc.) to find the next available position.
void insert(HashTable* hashTable, int key) {
int index = hashFunction(key);
while(hashTable->flags[index] != 0) {
index = (index + 1) % SIZE; // 线性探测法
}
hashTable->data[index] = key;
hashTable->flags[index] = 1;
}
- Perform a search operation by finding the corresponding data in the hash table based on the given keyword.
int search(HashTable* hashTable, int key) {
int index = hashFunction(key);
while(hashTable->flags[index] != 0) {
if(hashTable->data[index] == key) {
return index;
}
index = (index + 1) % SIZE;
}
return -1; // 表示未找到
}
This way, a simple hash table can be created. In practical applications, it can be resized or deleted as needed.