#include <iostream>
using namespace std;
//利用线性探测法
typedef int keyType;
typedef struct {
keyType key;
}HashTable,*HashTree;
class Hash {
public:
int curTable;//当前
//定义哈希函数
HashTree hashTable;
int maxTable;//表长
Hash(int length) {
curTable = 0;
maxTable = length;
hashTable=new HashTable[length];
for (int i = 0; i < length; i++)//初始化数值全为-1表示单元为空
hashTable[i].key = -1;
}
~Hash() {
delete[]hashTable;
hashTable = NULL;
}
//除留余数法
int H(int key) {
return key % 7;
}//原来该落下的位置
int hash(int key,int time) {
return pow(time+1, 2);
}//增量
bool isFull() {
return curTable == maxTable;
}
bool insert(int key) {
if (isFull()) return false;
int index = H(key);//原来该落的位置
if (hashTable[index].key== -1) {//未被赋值
hashTable[index].key = key;
return true;
}
else {
int newindex=0;
int time = 0;
while (true) {
newindex = (index + hash(key,time++)) % maxTable;
if (hashTable[newindex].key == -1) {
hashTable[newindex].key = key;
break;
}
}
}
curTable++;
}
void display()
{
for (int i = 0; i < maxTable; i++)
{
cout << i;
if (hashTable[i].key != -1)
cout << "---->" << hashTable[i].key;
cout << endl;
}
}
};
//###重点:散列表的查找###//
int searchHash(Hash & h, keyType data) {
//如果成功,则放回单元标号,否则返回-1
int H0 = 0;
H0= h.H(data);
if (h.hashTable[H0].key == -1) return -1;//没有存在
else if (h.hashTable[H0].key == data) return H0;//找到是在H0处
else{
for (int i = 1; i < h.maxTable; i++) {
//按照线性探测法计算下一个散列地址Hi
int Hi = (H0 + i) % h.maxTable;
if (h.hashTable[Hi].key == -1) return -1;
else if (h.hashTable[Hi].key == data) return Hi;
}
return -1;
}
}
int main() {
//针对课本课后习题
/*
对9,1,23,14,55,20,84,27,采用散列函数H(KEY)=KEY%7,表长度为10,开放地址法的二次探测法处理冲突
*/
int a[] = { 9,1,23,14,55,20,84,27 };
int n = sizeof(a) / sizeof(a[0]);
cout << "n=" << n << endl;
Hash h(10);
for (int i = 0; i < n; i++)
h.insert(a[i]);
h.display();
keyType data;
cout << "Please input the number you wanna locate" << endl;
while (cin>>data) {
if (searchHash(h, data) == -1) {
cout << "不存在" << endl;
}
else
cout <<data<< " locates at hashTable[" << searchHash(h, data) <<"]"<< endl;
cout << "Please input the number you wanna locate" << endl;
}
return 0;
}
基于开发地址法的散列表的查找
最新推荐文章于 2023-08-10 08:00:00 发布