题目描述
采用除留余数法(H(key)=key %n)建立长度为n的哈希表,处理冲突用链地址法。建立链表的时候采用尾插法。
输入
第一行为哈西表的长度m; 第二行为关键字的个数n; 第三行为关键字集合; 第四行为要查找的数据。
输出
如果查找成功,输出该关键字所在哈希表中的地址和比较次数;如果查找不成功,输出-1。
#include<bits/stdc++.h>
using namespace std;
int main() {
int hash[100][100],a[1005], data, pos = 0, m, n;
cin>>m>>n;
for (int i = 0; i < n; ++i){
for (int j = 0; j < n; ++j) hash[i][j] = n + 1;
}
for (int i = 0; i < n; ++i){
cin>>a[i];
int pos = 0;
while(hash[a[i] % n][pos] != n + 1) pos ++;
hash[a[i] % n][pos] = a[i];
}
cin>>data;
while(hash[data % n][pos] != data && pos < n) pos ++;
if(hash[data % n][pos] == data) cout<<data % n << "," << pos + 1;
else cout<< -1;
return 0;
}