用C语言写一个关于哈希表的创建,显示,插入,查询,删除程序
时间: 2023-06-03 09:08:14 浏览: 192
好的,我可以和你分享一些有关哈希表的C语言代码。这里是一个简单的哈希表示例,包含以下功能:创建哈希表、显示哈希表、插入数据、查询数据、删除数据。
```
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
//哈希表节点
typedef struct node {
int key; //哈希表键值
int value; //哈希表值
struct node* next;
}Node;
//哈希表
typedef struct hash_table {
Node* head[SIZE];
}HashTable;
//哈希表创建初始化
HashTable* create_table() {
HashTable* table = (HashTable*)malloc(sizeof(HashTable));
for (int i = 0; i < SIZE; i++) {
table->head[i] = NULL;
}
return table;
}
//哈希函数
int hash_func(int key) {
return key % SIZE;
}
//哈希表显示
void display_table(HashTable* table) {
for (int i = 0; i < SIZE; i++) {
printf("Bucket %d : ", i);
Node* current_node = table->head[i];
if (current_node == NULL) {
printf("(empty)\n");
}
else {
while (current_node != NULL) {
printf("(%d, %d) ", current_node->key, current_node->value);
current_node = current_node->next;
}
printf("\n");
}
}
}
//哈希表插入
void insert_data(HashTable* table, int key, int value) {
int index = hash_func(key);
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->key = key;
new_node->value = value;
new_node->next = NULL;
if (table->head[index] == NULL) {
table->head[index] = new_node;
return;
}
Node* current_node = table->head[index];
while (current_node->next != NULL) {
current_node = current_node->next;
}
current_node->next = new_node;
}
//哈希表查询
int find_data(HashTable* table, int key) {
int index = hash_func(key);
Node* current_node = table->head[index];
while (current_node != NULL) {
if (current_node->key == key) {
return current_node->value;
}
current_node = current_node->next;
}
return -1;
}
//哈希表删除
void delete_data(HashTable* table, int key) {
int index = hash_func(key);
Node* current_node = table->head[index];
Node* previous_node = NULL;
if (current_node == NULL) {
printf("Key not found.\n");
return;
}
if (current_node->key == key) {
table->head[index] = current_node->next;
free(current_node);
return;
}
while (current_node != NULL && current_node->key != key) {
previous_node = current_node;
current_node = current_node->next;
}
if (current_node == NULL) {
printf("Key not found.\n");
return;
}
previous_node->next = current_node->next;
free(current_node);
}
//主函数测试哈希表
int main() {
//创建哈希表
HashTable* table = create_table();
//插入数据
insert_data(table, 1, 10);
insert_data(table, 2, 20);
insert_data(table, 3, 30);
insert_data(table, 4, 40);
//显示哈希表
printf("--- Initial Hash Table ---\n");
display_table(table);
//查询数据
printf("--- Searching Value for Key 3 ---\n");
int value = find_data(table, 3);
if (value != -1) {
printf("Value : %d\n", value);
}
else {
printf("Key not found.\n");
}
//删除数据
printf("--- Deleting Key 3 ---\n");
delete_data(table, 3);
//显示哈希表
printf("--- Final Hash Table ---\n");
display_table(table);
return 0;
}
```
注意,本示例为基础代码,您可以按照自己的需求对其进行修改和扩展。
阅读全文