From f92554b0f438e30a91bbfcda3fde5b88f6f08d06 Mon Sep 17 00:00:00 2001 From: Hongcheng Date: Tue, 3 Oct 2023 23:01:35 +0800 Subject: [PATCH] ADD file via upload --- test_hash.c | 160 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 test_hash.c diff --git a/test_hash.c b/test_hash.c new file mode 100644 index 000000000..ebd6578a2 --- /dev/null +++ b/test_hash.c @@ -0,0 +1,160 @@ +//拉链法 建立长度为n的哈希表并解决哈希冲突 +#include +#include +#include +#include +#define N -32768 +#define max 10 + +//结点结构体 +typedef struct LNode +{ + int data;//存储值 + struct LNode *next; +}LNode,*Linklist; + +//构建哈希表结构体 +typedef struct HashTable +{ + Linklist list; + int count;//记录该结点下共发生冲突结点个数 +}HashTable; + +//哈希函数 计算 +int Hash(int key) +{ + return key % 5; +} + +//初始化哈希表函数 +void InitHashTable (HashTable *h) +{ + //初始化链表表头 + h->list=(LNode *)malloc(max * sizeof(LNode)); + h->count=0; + + //初始化 + for(int i=0;ilist[i].data=N; + h->list[i].next=NULL; + } + printf("哈希表已初始化\n"); +} + +//关键字插入函数 +void InsertKey(HashTable *h,int key,int i) +{ + //获取下标 + int id=Hash(key); + printf("\n插入关键字%d,哈希地址=%d\n",key,id); + //判断是否插入关键字 + if(h->list[id].data==N) + { + //未发生冲突 + h->list[id].data=key; + printf("第%d个数已插入\n",i+1,id); + } + else + { + //发生冲突,插入新结点 + LNode *node; + node=(LNode *)malloc(sizeof(LNode)); + node->data=key; + node->next=h->list[id].next; + h->list[id].next=node; + printf("发生冲突,第%d个数已插入\n",i+1,id); + } + h->count++; +} + +//关键字查找 +LNode *Search(HashTable h,int key) +{ + int id=Hash(key); + LNode *head=&h.list[id];//获取头结点 + while(head!=NULL&&head->data!=key)//找到关键字对应结点 + { + head=head->next; + } + return head; + +} + +//打印哈希表 +void show(HashTable h) +{ + for(int i=0;i<5;i++) + { + printf("%d\t",i); + } + printf("\n"); + LNode *node; + int j=0; + int count=0; + int flag=1; + while(flag) + { + flag=0; + for(int i=0;inext; + j++; + } + if(node&&node->data!=N) + { + printf("%d\t",node->data); + flag=1; + } + else + { + printf(" \t"); + } + } + count++; + printf("\n"); + } +} + +int main() +{ + system("chcp 65001"); + int key;//关键字 + HashTable h; + InitHashTable(&h); + printf("输入关键字构建哈希表:\n"); + srand((unsigned)time(NULL)); + for(int i=0;i