目录
一、结构体
typedef struct node
{
int key;
struct node* next;
}node,*pnode;
二、初始化哈希表
#define HASHMAX 13//根据数据长度修改
void init_hash(pnode hash[])
{
if (hash == NULL)
{
printf("入参为空\n");
return;
}
for (int i = 0; i < HASHMAX; i++)
{
hash[i] = NULL;
}
}
三、输入
#define HASHMAX 13//根据数据长度修改
void insert_hash(pnode hash[],int key)
{
if (hash == NULL)
{
printf("入参为空\n");
return;
}
int i = key%HASHMAX;
pnode p = (pnode)malloc(sizeof(node));
p->key = key;
p->next = hash[i];
hash[i] = p;
}
四、输出
#define HASHMAX 13//根据数据长度修改
void print_hash(pnode hash[])
{
if (hash == NULL)
{
printf("入参为空\n");
return;
}
for (int i = 0; i < HASHMAX; i++)
{
printf("hash[%d]->",i);
pnode temp = hash[i];
while (temp != NULL)
{
printf("%d->",temp->key);
temp = temp->next;
}
printf("^\n");
}
}
五、查找
#define HASHMAX 13//根据数据长度修改
void srearch_hash(pnode hash[],int key)
{
if (hash == NULL)
{
printf("入参为空\n");
return;
}
int i = key%HASHMAX;
pnode p = hash[i];
while (p != NULL && p->key != key)
{
p = p->next;
}
if(p==NULL)
{
printf("要查找的数据不在哈希表中\n");
}
else
{
printf("要查找的元素在哈希表中\n");
}
}
六、main.c文件
#define ARRMAX 10 //根据数据修改
int main(int argc, char const *argv[])
{
pnode hash[HASHMAX];
int arr[ARRMAX] = {30,39,57,47,92,1,23,12,22,31};
init_hash(hash);
for (int i = 0; i < ARRMAX; i++)
{
insert_hash(hash,arr[i]);
}
print_hash(hash);
return 0;
}