#include <iostream>
#include <cmath>
using namespace std;
const int MaxsSize=11;
class HashTable1
{
public:
HashTable1();
int Insert(int k);
int Search(int k);
void Print();
private:
int H(int k); //散列函数
int ht[MaxsSize]; //闭散列表
};
HashTable1::HashTable1()
{
for(int i=0;i<MaxsSize;i++)
ht[i]=0;
}
int HashTable1::H(int k)
{
return k%11;
}
void HashTable1::Print()
{
for (int i=0; i<MaxsSize; i++) {
cout<<ht[i]<<" ";
}
cout<<endl;
}
int HashTable1::Search(int k)
{
int i,j=H(k);
i=j;
while (ht[i]!=0) {
if(ht[i]==k)
return i;
else
i=(i+1)%MaxsSize;
}
return -1;
}
int HashTable1::Insert(int k)
{
int i,j=H(k);
i=j;
while (ht[i]!=0){
if(ht[i]==k)return -1;
else
i=(i+1)%MaxsSize;
}
ht[i]=k;
return i;
}
int main()
{
HashTable1 ha;
int a[6]={23,12,4,5,28,1};
for (int i=0; i<6; i++) {
ha.Insert(a[i]);
}
ha.Print();
cout<<ha.Search(4)<<endl;
cout<<ha.Search(20)<<endl;
ha.Print();
}
C++数据结构——散列查找(闭散列表)
最新推荐文章于 2022-03-06 18:25:14 发布