#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define DEFAULT_SIZE 16
/* *
* double link
* */
typedef struct list_node_s
{
int key;
void *data;
struct list_node_s *prev;
struct list_node_s *next;
} list_node_t;
typedef struct hash_table_s
{
list_node_t **hash_map;
int table_size;
} hash_talbe_t;
int hash_func(int key, int table_size) {
return (key % table_size);
}
hash_talbe_t *init_hash(int table_size) {
if (table_size <= 0) {
return NULL;
}
hash_talbe_t *hash_map = (hash_talbe_t *)calloc(1, sizeof(hash_talbe_t));
if (hash_map == NULL) {
return NULL;
}
hash_map->table_size = table_size;
hash_map->hash_map = (list_node_t **)calloc(1, sizeof(list_node_t *) * table_size);
if (hash_map->hash_map == NULL) {
free(hash_map);
return NULL;
}
return hash_map;
}
list_node_t *find(hash_talbe_t *hash_map, int key) {
if (!hash_map) {
return NULL;
}
int index = hash_func(key, hash_map->table_size);
if (hash_map->hash_map[index] == NULL) {
return NULL;
} else {
list_node_t *head = hash_map->hash_map[index];
if (head->key == key) {
return head;
}
list_node_t *tmp = head->next;
while (tmp != head) {
if (key == tmp->key) {
return tmp;
}
tmp = tmp->next;
}
}
return NULL;
}
void insert(hash_talbe_t *hash_map, int key, void *value) {
if (!hash_map || !value) {
return;
}
list_node_t *node = find(hash_map, key);
if (node) {
node->data = value;
return;
}
node = (list_node_t *)calloc(1, sizeof(list_node_t));
if (node == NULL) {
return;
}
node->data = value;
node->key = key;
node->prev = node->next = node;
int index = hash_func(key, hash_map->table_size);
if (hash_map->hash_map[index] == NULL) {
hash_map->hash_map[index] = node;
} else {
list_node_t *head = hash_map->hash_map[index];
node->prev = head->prev;
node->next = head->prev->next;
head->prev->next = node;
head->prev = node;
}
}
void delete(hash_talbe_t *hash_map, int key) {
if (!hash_map) {
return;
}
list_node_t *node = find(hash_map, key);
if (node == NULL) {
return;
}
node->prev->next = node->next;
node->next->prev = node->prev;
free(node);
}
int main(void) {
char *elements[] = {
(char *)"xiaomi",
(char *)"huawei",
(char *)"dajiang"
};
hash_talbe_t *hash_map = init_hash(DEFAULT_SIZE);
insert(hash_map, 1, elements[0]);
insert(hash_map, 2, elements[1]);
insert(hash_map, 3, elements[2]);
delete(hash_map, 1);
for (int i = 0; i < DEFAULT_SIZE; i++) {
list_node_t *node = find(hash_map, i);
if (node) {
printf("key:%d, value:%s\n", node->key, (char *)node->data);
}
}
return 0;
}
c实现hash函数双链表
最新推荐文章于 2024-10-16 11:55:59 发布