散列
数据结构与算法分析
散列
请随机生成30个1~50之间大小不等的整数,以散列的方式存入一个长度为20的结构体数组,请按你的思路构造散列(哈希)函数、使用拉链法解决冲突,然后输入一个整数进行散列查找并打印出查找结果(找到的话需要输出数据存储的位置)。
#include <bits/stdc++.h>
int a[31];
struct node
{
int val;
node *next;
}*head[21];
void Insert(int x)
{
int pos = ceil(x/2.5);
if(head[pos] == NULL )
{
head[pos] = (struct node*)malloc(sizeof (struct node));
head[pos] ->val = x;
head[pos] ->next = NULL ;
}
else
{
struct node* tmp = (struct node*)malloc(sizeof (struct node));
tmp->val = x;
tmp->next = head[pos];
head[pos] = tmp;
}
}
int query(int x)
{
int pos = ceil(x/2.5);
if(head[pos] == NULL ) return -1;
else
{
struct node *k = head[pos];
while(k)
{
if(k->val == x) return pos;
k = k->next;
}
return -1 ;
}
}
int main()
{
srand(time(NULL)) ;
for(int i = 1; i <= 20; i ++ ) head[i] = NULL ;
// std::cout << ceil(8/2.5) << std::endl;
for(int i = 1; i <= 30; i ++ )
{
a[i] = rand() % 50 + 1;
std::cout << a[i] << " ";
std::cout << "\n";
Insert(a[i]);
}
int num;
scanf("%d", &num);
int o = query(num);
if(o == -1) printf("ERROR\n");
else printf("the pos of this num is %d", o);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具