本文将介绍数据结构中的哈希,哈希由hash与chunk组成
哈希数据存储的数量为一组hash的数据×chunk的大小:HASH_NUM * CHUNK_NUM
下面从哈希的结构、初始化、创建、增、删、遍历、释放用法进行代码梳理
1.哈希的结构
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
int data; //用于存数据
struct node *next; //用于存指针
} hash_t;
2.定义与声明
#define HASH_NUM 4096
#define CHUNK_NUM 1024
3.哈希的初始化:
初始化一组hash和chunk
void hashInit(){
//1.初始化哈希
hash_t **h = (hash_t **)malloc(HASH_NUM * CHUNK_NUM);
int i = 0;
for(i = 0; i < HASH_NUM; i++){
//2.初始化chunk
h[i] = (struct node *)malloc(sizeof(struct node));
h[i]->next = NULL;
}
}
4.哈希插入:
计算出key值,再创建一个点,再插入数据
void hashInsertNode(hash_t **h, int data)
{
int key = data % HASH_NUM;
struct node * p = h[key];
//从头插入数据
struct node * temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
temp->next = p->next;
p->next = temp;
}
5.哈希查找:
计算出key值,while循环找到对应的数据
int hashFindNode(hash_t **h, int data)
{
int key = data % HASH_NUM; //得到key值
struct node *p = h[key]; //找到对应链表
//对比要查找的数据
while (p->next != NULL )
{
if (p->next->data == data)
{
//找到返回1
return 1;
}
p = p->next;
}
//没有找到返回0
return 0;
}
6.哈希的遍历打印
int travelHash(struct node *head)
{
if (head->next == NULL)
{
return -1;
}
//遍历链表,打印数据
while(head->next != NULL)
{
head = head->next;
printf("%d ", head->data);
}
putchar(10);
return 0;
}
7.哈希释放:
先遍历释放每个点,再释放整个hash
int freeHashData(struct node *head)
{
//如果链表后面没有数据,则不需要释放
if (head->next == NULL)
{
return 0;
}
while(head->next != NULL)
{
struct node *temp = head->next;
head->next = head->next->next;
free(temp);
temp = NULL;
}
return 0;
}
//释放整个哈希
free(h);