#include<iostream>
#include<iomanip>
using namespace std;
const int P = 7;
const int DefaultSize = 7;
enum KindOfStatus{Active,Empty,Deleted};
class HashTable
{
public:
HashTable(const int d,int sz = DefaultSize)
{
divitor =d;
TableSize = sz;
CurSize = 0;
ht = new int[TableSize];
info = new KindOfStatus[TableSize];
for (int i=0;i<TableSize;++i)
{
info[i]= Empty;
}
}
~HashTable()
{
delete []ht;
delete []info;
}
public:
int Hash(const int &key)
{
int index = key % divitor;
if (info[index] == Empty)
return index;
if (info[index]== Active && ht[index] == key)
return index;
int i=index;
do
{
i=(i+1) % TableSize;
if (info[i] == Empty)
return i;
if (info[i] ==Active && ht[i]== key)
return i;
}while(i != index);
return i;
}
void Show()
{
cout<<setw(7)<<"info:";
for(int i=0; i<TableSize; ++i)
{
if (info[i] == Active)
cout<<setw(4)<<"A";
else if (info[i] == Empty)
cout<<setw(4)<<"E";
else
cout<<setw(4)<<"D";
}
cout<<endl;
cout<<setw(7)<<"value:";
for (i=0;i<TableSize; ++i)
{
if (info[i] ==Active)
cout<<setw(4)<<ht[i];
else
cout<<setw(4)<<" ";
}
cout<<endl;
cout<<setw(7)<<"ht:";
for (i=0;i<TableSize;++i)
{
cout<<setw(4)<<i;
}
cout<<endl;
}
void Insert(const int &key)
{
int index =Hash(key);
if (info[index] == Active && ht[index] == key)
{
cout<<"元素存在,不能插入!"<<endl;
return;
}
if (info[index]== Active)
{
cout<<"表满,不能插入!"<<endl;
return;
}
else
{
ht[index] = key;
info[index]= Active;
CurSize++;
}
}
int Find(const int &key)
{
int index=Hash(key);
if (info[index] ==Empty)
{
cout<<"此位置空,无元素,不能查找!"<<endl;
return 0;
}
if (info[index]==Active && ht[index] == key)
{
cout<<"index="<<index<<endl;
return index;
}
else
{
cout<<"表中无此元素!"<<endl;
return 0;
}
}
void Remove(const int &key)
{
int i=Find(key);
if (info[i] ==Empty)
{
cout<<"此位置空,无元素,不能删除!"<<endl;
return;
}
if (info[i] == Active && ht[i] == key)
{
info[i] = Deleted;
CurSize--;
}
else
{
cout<<"表中无此元素,无法删除!"<<endl;
}
}
void MakeEmpty()
{
for (int i=0;i<TableSize;++i)
{
info[i] = Empty;
CurSize =0;
}
}
private:
int divitor;
int TableSize;
int CurSize;
int *ht;
KindOfStatus *info;
};
void main()
{
HashTable ht(P);
ht.Insert(1);
ht.Insert(2);
ht.Insert(8);
ht.Insert(15);
//ht.Insert(22);
ht.Show();
ht.Find(8);
ht.Show();
ht.Remove(15);
ht.Show();
ht.MakeEmpty();
ht.Show();
}
哈希表的线性探查法搜索算法
最新推荐文章于 2023-03-08 16:16:14 发布