ADD file via upload

This commit is contained in:
LuStar 2023-10-03 02:43:10 +08:00
parent b96d1825ef
commit b5662e2e4f
1 changed files with 166 additions and 0 deletions

166
test_hash.c Normal file
View File

@ -0,0 +1,166 @@
#include <stdio.h>
#include <stdlib.h>
#include "test_hash.h"
//创建hash表
hashType **create_hash()
{
hashType **h = (hashType **)malloc(N * ADDR_SIZE);
for (int i = 0; i < N; i++)
{
h[i] = (struct node *)malloc(sizeof(struct node));
h[i]->next = NULL;
}
return h;
}
//插入数据
int insert_hash_table(hashType **h, int data)
{
int key = data % N;
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;
return 0;
}
//遍历
int show_hash_table(struct node *head)
{
//如果链表后面没有数据,则用---0---表示链表存在但是没有数据
if (head->next == NULL)
{
puts("---0---");
return -1;
}
//打印“->”呈现链表形式
int flag= 0;
//遍历链表,打印数据
while(head->next != NULL)
{
if(flag==1)printf("->");
head = head->next;
printf("%d", head->data);
flag= 1;
}
putchar(10);
return 0;
}
//释放链表节点
void free_hash_table(struct node *head)
{
//如果链表后面没有数据,则无需释放
if (head->next == NULL)
{
return;
}
//遍历这个链表-头删法释放
while(head->next != NULL)
{
//定义一个结构体指针变量 来指向这个即将被删除的结构体 以便释放
struct node *temp = head->next;
head->next = head->next->next;
printf("--%d--wil be free\n",temp->data);
free(temp);
temp = NULL;
}
}
//查找数据
int search_hash_table(hashType **h, int data)
{
int key = data % N; //数据对质数取余,得到键值
struct node *p = h[key]; //找到对应链表
//对比要查找的数据
while (p->next != NULL )
{
if (p->next->data == data)
{
return 1;//找到返回1
}
p = p->next;
}
//没有找到返回0
return 0;
}
//11个数据那么m : n/0.75 = 14 最大质数为13
int main()
{
int a[11] = {100, 34, 14, 45, 46, 98, 68, 69, 7, 31, 26};
//创建hash表
hashType **h = create_hash();
for (int i=0;i<11;i++)
{
insert_hash_table(h, a[i]);//链表的插入
}
//打印hash表--无实际意义
printf("-------This is hash table--------------------\n");
for (int i = 0; i < N; i++)
{
printf("hash code:%d; value:",i);
show_hash_table(h[i]);//链表的遍历
}
printf("--------hash table is finished--------------------\n");
printf("数组数据如下-->用于测试,无实质意义,遍历HASH表也是<---\n");
for(int i=0;i<11;i++)
{
printf("%d ",a[i]);
}
putchar(10);
printf("---Looking for values in the hash table---\n");
printf("Determine if data 98 exists");
//--查找--
if(search_hash_table(h, 98) == 1)
{
printf("---data 98 is exists---\n");
}
else
{
printf("---data 98 is not exists---\n");
}
printf("Determine if data 1 exists");
//--查找--
if(search_hash_table(h, 1) == 1)
{
printf("---data 1 is exists---\n");
}
else
{
printf("---data 1 is not exists---\n");
}
printf("Determine if data 34 exists");
//--查找--
if(search_hash_table(h, 34) == 1)
{
printf("---data 34 is exists---\n");
}
else
{
printf("---data 34 is not exists---\n");
}
printf("---The hash table will be free---\n");
//链表的释放
for(int i = 0;i < 11;i ++)
{
free_hash_table(h[i]);
}
printf("---链表释放完成---\n");
free(h);
printf("---指针数组释放---\n");
return 0;
}