用C实现一个哈希表
以下是一个简单的C语言哈希表实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 1000
typedef struct {
int key;
int value;
} node;
node* hash_table[TABLE_SIZE];
int hash_function(int key) {
return key % TABLE_SIZE;
}
void insert(int key, int value) {
int index = hash_function(key);
node* new_node = (node*)malloc(sizeof(node));
new_node->key = key;
new_node->value = value;
hash_table[index] = new_node;
}
int search(int key) {
int index = hash_function(key);
if (hash_table[index] != NULL && hash_table[index]->key == key) {
return hash_table[index]->value;
}
return -1;
}
void delete(int key) {
int index = hash_function(key);
if (hash_table[index] != NULL && hash_table[index]->key == key) {
node* temp = hash_table[index];
hash_table[index] = NULL;
free(temp);
}
}
int main() {
insert(1, 10);
insert(2, 20);
insert(3, 30);
printf("%d\n", search(2));
delete(2);
printf("%d\n", search(2));
return 0;
}
该哈希表使用了一个数组来存储节点,每个节点包含一个键和一个值。哈希函数使用取模运算,将键映射到数组中的索引位置。插入操作创建一个新的节点并将其放置在哈希表中正确的索引位置,搜索操作从哈希表中查找给定键的值,删除操作从哈希表中删除给定键的节点
原文地址: https://www.cveoy.top/t/topic/ehob 著作权归作者所有。请勿转载和采集!