Description
定义哈希函数为H(key) = key%11,输入表长(大于、等于11)。输入关键字集合,用线性探测再散列构建哈希表,并查找给定关键字。
–程序要求–
若使用C++只能include一个头文件iostream;若使用C语言只能include一个头文件stdio
程序中若include多过一个头文件,不看代码,作0分处理
不允许使用第三方对象或函数实现本题的要求
Input
测试次数t
每组测试数据为:
哈希表长m、关键字个数n
n个关键字
查找次数k
k个待查关键字
Output
对每组测试数据,输出以下信息:
构造的哈希表信息,数组中没有关键字的位置输出NULL
对k个待查关键字,分别输出:0或1(0—不成功,1—成功)、比较次数、查找成功的位置(从1开始)
Sample
Input
1 12 10 22 19 21 8 9 30 33 4 15 14 4 22 56 30 17
Output
22 30 33 14 4 15 NULL NULL 19 8 21 9 1 1 1 0 6 1 6 2 0 1
Hint
注意查找的终止条件,comparison应该小于hashTable的len,避免死循环。
Code
#include<iostream>
using namespace std;
void init(int*& hashTable, int m) {
for (int i = 0; i < m; i++) {
hashTable[i] = -1;
}
}
// 线性探测再散列插入
void insert(int* hashTable, int m, int key) {
int index = key % 11;
while (hashTable[index] != -1) {
index = (index + 1) % m;
}
hashTable[index] = key;
}
// 线性探测再散列查找
void search(int*& hashTable, int m, int key, int& comparisons) {
int index = key % 11;
comparisons = 1;
while (hashTable[index] != -1 && hashTable[index] != key) {
if (comparisons >= m)
break;
index = (index + 1) % m;
comparisons++;
}
if (hashTable[index] == key) {
cout << "1 " << comparisons << " " << index + 1;
}
else
cout << "0 " << comparisons ;
cout << endl;
}
void print(int* hashTable, int m) {
for (int i = 0; i < m; i++) {
if (hashTable[i] != -1)
cout << hashTable[i] << " ";
else cout << "NULL ";
}
cout << endl;
}
int main() {
int t, m, n, k, key;
cin >> t;
while (t--) {
cin >> m >> n;
int* hashTable = new int[m];
init(hashTable, m);
/* ...n个关键字... */
for (int i = 0; i < n; i++) {
cin >> key;
insert(hashTable, m, key);
}
print(hashTable, m);
cin >> k;
while (k--) {
cin >> key;
/* 查找key */
int comparsions;
search(hashTable, m, key, comparsions);
}
delete[]hashTable;
}
return 0;
}