哈希表的代码写完,写出给出关键字,找到该关键字在哈希表(指针数组)中下标的位置,以及在链表中的位置。

快速排序

折半查找

思维导图

#ifndef __HASH_H__
#define __HASH_H__
#include <stdio.h>
#include <stdlib.h>
#define MAX 13
typedef struct node
{
int data;
struct node *next;
}node,*node_p;
//1、存入哈希表
void insert(node_p H[],int key);
//申请结点的函数
node_p create_node(int data);
//2、输出哈希表
void show(node_p *H);
//3、查找元素
int search_hash(node_p *H,int data);
#endif
#include "hash.h"
int main()
{
int arr[]={25,51,8,22,26,67,11,16,54,41};
//确定哈希表的表长
int len = sizeof(arr)/sizeof(arr[0]);
int hash_len = len*4/3;
node_p H[MAX] = {0};
//1、循环把数据存入哈希表
for(int i=0;i<len;i++)
{
insert(H,arr[i]);
}
show(H);
search_hash(H,54);
return 0;
}
#include "hash.h"
//申请结点的函数
node_p create_node(int data)
{
node_p new = (node_p)malloc(sizeof(node));
if(new==NULL)
{
printf("空间申请失败\n");
return NULL;
}
new->data = data;
return new;
}
//1、存入哈希表
void insert(node_p H[],int key)
{
//数据要存入哈希表中指定下标的位置
int i = key%MAX;
//申请结点
node_p new = create_node(key);
//头插
new->next = H[i];
H[i] = new;
}
//2、输出哈希表
void show(node_p *H)
{
//1、入参为空判断
if(*H==NULL)
{
printf("入参有误\n");
return;
}
//循环哈希表(指针数组)
for(int i=0;i<MAX;i++)
{
//输出指针数组指向的链表
node_p p = H[i];
while(p!=NULL)
{
printf("%d->",p->data);
p=p->next;
}
printf("NULL\n");
}
}
//3、查找元素
int search_hash(node_p *H,int data)
{
if(*H==NULL)
{
printf("入参有误\n");
return -1;
}
int i = data%MAX;
int pos=0;
node_p p=H[i];
while(p!=NULL)
{
if(data==p->data)
{
printf("H中i=%d的pos=%d\n",i,pos);
return pos;
}
p=p->next;
pos++;
}
printf("未找到,请检查\n");
}
本文介绍了如何使用C语言实现一个简单的哈希表,包括数据的插入、输出和查找功能,使用了指针数组和链表结构,同时提到了与之相关的算法如快速排序和折半查找。
6895

被折叠的 条评论
为什么被折叠?



