实验15-哈希查找与排序-
题目描述
给出一个数据序列,建立哈希表,采用求余法作为哈希函数,模数为11,哈希冲突用链地址法和表头插入
如果首次查找失败,就把数据插入到相应的位置中
实现哈希查找功能
输入
第一行输入n,表示有n个数据
第二行输入n个数据,都是自然数且互不相同,数据之间用空格隔开
第三行输入t,表示要查找t个数据
从第四行起,每行输入一个要查找的数据,都是正整数
输出
每行输出对应数据的查找结果
输入样例
6
11 23 39 48 75 62
6
39
52
52
63
63
52
输出样例
6 1
error
8 1
error
8 1
8 2
提示
注意,当两次输入要相同的查找数据,如果第一次查找不成功就会执行插入,那么第二次查找必然成功,且查找次数为1次(因为做表头插入)
例如示例数据中输入两次52,第一次查找失败就把52插入到位置8,第二次查找就成功了,所以第一次输出error,第二次就输出8 1
为什么第三次输入52会输出8 2
#include<iostream>
using namespace std;
struct node
{
int data;
int key;//余数!
struct node *next;
};
class Hash
{
node *T;
int n;
public:
Hash(int num){n=num;T=new node[n];}
void createhash()
{
int i,e;
for(i=0;i<n;i++)
{
cin>>e;
T[i].key=e%11;
T[i].data=e;
T[i].next=NULL;
}
}
void search(int e)
{
//cout<<e<<":"<<endl;
int flag=0,i,sum=0;
int realkey=e%11;
struct node *p=new node();
for(i=0;i<n;i++)
{
if(T[i].key==realkey)
{
flag=1;
p=&T[i];//查找的链表
while(p)
{
sum++;
if(p->data==e)
{
cout<<realkey<<" "<<sum<<endl;
break;
}
p=p->next;
}
if(p==NULL)
{
cout<<"error"<<endl;
insert(e,i);
}
break;
}
}
if(flag==0)//不在数据里,表头插入数据
{
cout<<"error"<<endl;
n=n+1;
T[n-1].data=e;
T[n-1].key=realkey;
T[n-1].next=NULL;
}
}
void insert(int e,int i)
{
node *p=new node();
p->next=T[i].next;
p->data=T[i].data;
T[i].data=e;
T[i].next=p;
//delete p;
}
};
int main()
{
int n,t;
cin>>n;
Hash H(n);
H.createhash();
cin>>t;
while(t--)
{
int e;
cin>>e;
H.search(e);
}
return 0;
}