目录
hash.h
#ifndef __HASH_H__
#define __HASH_H__
// 哈希表
#include <stdio.h>
#include <stdlib.h>
#define N 11 // 要存的数据个数
#define PRIME 13 // 哈希表长度 = ( 数据个数(11) / 填充因子(0.75) )最大的质数
#define datatype int
typedef struct node{
datatype data; // 节点数据
int key; // 哈希表中,该节点的位置下标
struct node* next;
} linknode_t;
typedef struct {
linknode_t hash[PRIME]; // 哈希表
} linkHash_t;
/// @brief 创建哈希表
/// @return 表地址
linkHash_t * create_hash();
/// @brief 插入数据
/// @param hs 哈希表
/// @param data 待插入数据
/// @return 成功0 失败-1
int insert_hash(linkHash_t *hs, datatype data);
/// @brief 查找元素
/// @param hs 哈希表
/// @param data 要查找的数据
/// @return 元素地址
linknode_t* seek_data_hash(linkHash_t *hs, datatype data);
#endif // !__HASH_H__
hash.c
#include "hash.h"
#include <string.h>
// 创建哈希表
linkHash_t* create_hash()
{
// 1.创建哈希表
linkHash_t* hs;
// 2.malloc
if ((hs = (linkHash_t*)malloc(sizeof(linkHash_t))) == NULL) {
printf("hash malloc failure\n");
return NULL;
}
memset(hs, 0, sizeof(linkHash_t));
return hs;
}
// 插入数据
int insert_hash(linkHash_t* hs, datatype data)
{
// 1.校验哈希表
if (hs == NULL) {
printf("hash is NULL\n");
return -1;
}
// 2.创建节点
linknode_t* node;
if ((node = (linknode_t*)malloc(sizeof(linknode_t))) == NULL) {
printf("node malloc failure\n");
return -1;
}
node->data = data;
node->key = data % PRIME;
node->next = NULL;
// 3.获取哈希表对应位置头节点
linknode_t* temp = &(hs->hash[node->key]);
// 4.在链表中,找到新节点要插入位置的前一个节点
while (temp->next && temp->next->data < node->data) {
temp = temp->next;
}
// 5.判断链表中只有一个节点的情况
if (!temp->next) {
// 6.比较两个节点的数据大小
if (node->data < temp->data) {
// 7.新节点数据最小,将节点插入到前面
hs->hash[node->key] = *node;
node->next = temp;
return 0;
}
}
// 8.已找到要插入位置的前一个节点,开始插入节点
node->next = temp->next;
temp->next = node;
return 0;
}
// 查找元素
linknode_t* seek_data_hash(linkHash_t* hs, datatype data)
{
// 1.校验哈希表
if (hs == NULL) {
printf("hash is NULL\n");
return NULL;
}
// 2.开始查找
linknode_t* temp = &(hs->hash[data % PRIME]);
while (temp->next && temp->next->data != data) {
temp = temp->next;
}
if (temp->next == NULL) {
printf("data:%d is nothingness\n", data);
return NULL;
} else {
return temp->next;
}
}
main.c
#include "hash.h"
int main(int argc, const char* argv[])
{
// 0.创建哈希表
linkHash_t* hs = create_hash();
if (hs == NULL) {
return -1;
}
// 1.插入元素
datatype array[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
for (int i = 0; i < sizeof(array) / sizeof(datatype); i++) {
insert_hash(hs, array[i]);
}
datatype i = 0;
linknode_t* node;
while (1) {
printf("请输入要查找的数:");
scanf("%d", &i);
node = seek_data_hash(hs, i);
if (node == NULL) {
continue;
}
printf("已找到:data=%d key=%d node->data=%d node->key=%d\n", i, i % PRIME, node->data, node->key);
}
return 0;
}