题目描述
给出一个数据序列,建立哈希表,采用求余法作为哈希函数,模数为11,哈希冲突用链地址法和表尾插入
如果首次查找失败,就把数据插入到相应的位置中
实现哈希查找与增补功能
输入
第一行输入n,表示有n个数据
第二行输入n个数据,都是自然数且互不相同,数据之间用空格隔开
第三行输入t,表示要查找t个数据
从第四行起,每行输入一个要查找的数据,都是正整数
输出
每行输出对应数据的查找结果,每个结果表示为数据所在位置[0,11)和查找次数,中间用空格分开
样例输入
6
11 23 39 48 75 62
6
39
52
52
63
63
52
样例输出
6 1
error
8 1
error
8 2
8 1
思路:
用一个结构体数组m表示哈希表
struct Node{
int data;
struct Node *next;
};
建表:
建立一个结构体数组m,初始化长度为11,m[i]即为键值为i的链表
每次输入一个value,取key为value%11
m[key]即为要存放的链表
从m[key]的最后插入输入的value
查找:
还是依据value取key
从m[key]的next往后找,如果找到,则返回,如果没找到,则在表尾插入value
code:
#include <iostream>
using namespace std;
void test(int t)
{
struct Node{
int data;
struct Node *next;
};
int n;
n=t;
struct Node *m;
m = new Node[11];
for(int i=0;i<n;i++) //hash表数组每个元素的next都初始化为NULL
{
m[i].next=NULL;
}
int value,key;
struct Node *t1,*t2;
for(int i=0;i<n;i++) //建表
{
cin>>value;
key=value%11; //取key
t1= new Node; //生成新结点,插入到m[key]尾部
t1->data=value;
t1->next=NULL;
t2=m[key].next;
if(t2 == NULL)
m[key].next=t1;
else
{
while(t2->next != NULL)
t2=t2->next;
t2->next=t1;
}
}
int search_num,search_time;
cin>>search_num;
for(int i=0;i<search_num;i++) //查询
{
cin>>value;
key=value%11; //取key
search_time=0;
t1=m[key].next;
if(t1==NULL) //头结点需要另外判断是否找到
{
t2=new Node;
t2->data=value;
t2->next=NULL;
m[key].next=t2;
cout<<"error"<<endl;
}
else
{
while(t1!=NULL)
{
search_time++;
if(t1->data==value) //若找到,则返回
{
cout<<key<<' '<<search_time<<endl;
break;
}
else
{
t2=t1;
t1=t1->next;
}
}
if(t1==NULL) //若没找到,则插到尾部
{
t1=new Node;
t1->data=value;
t1->next=NULL;
t2->next=t1;
cout<<"error"<<endl;
}
}
}
delete[] m;
}
int main()
{
int t;
while (cin>>t)
{
test(t);
}
return 0;
}