散列
数据结构与算法分析
散列
请随机生成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;
}