您的位置:首页 > 理论基础 > 数据结构算法

[C++]数据结构:散列表HashTable的实现与简单应用

2012-12-05 18:02 645 查看
#include <iostream>
using namespace std;

template<class E,class K>
class HashTable{
public:
HashTable(int divisor=11);
~HashTable(){delete[]ht;delete[]empty;}
bool Search(const K&k,E&e)const;
HashTable<E,K>& Insert(const E&e);
int hSearch(const K&k)const;
int D;			//散列函数的除数
E *ht;			//散列数组
bool *empty;	//一维数组
void Output(ostream& out)const;
};

//构造函数
template<class E,class K>
HashTable<E,K>::HashTable(int divisor){
D = divisor;

//分配散列数组
ht = new E[D];
empty=new bool[D];

//将所有桶置空
for (int i = 0;i<D;i++){
empty[i]=true;
}
}

//查找一个开地址表
//如果存在则返回k的位置
//否则返回插入点(如果有足够的空间)
//hSearch满足以下三种情况之一返回b号桶
//1)empty[b]=false且ht[b]的关键字值为k
//2)表中没有关键字为k的元素,empty[b]=true,可把关键字为k的元素插入b号桶中
//3)表中没有关键字为k的元素,empty[b]为false,ht[b]的关键字值不等于k,且表已满
template<class E,class K>
int HashTable<E,K>::hSearch(const K&k)const{
int i = k%D;			//起始桶
int j=i;				//从起始桶开始
do{
if(empty[j]||ht[j]==k)
return j;
j=(j+1)%D;			//下一个桶

} while (j!=i);			//又返回起始桶

return j;				//表已经满了
}

//搜索与k相匹配的元素并放入e
//如果不存在则返回false
template<class E,class K>
bool HashTable<E,K>::Search(const K&k,E&e)const{
int b = hSearch(k);
if(empty[b]||ht[b]!=k)
return false;
e=ht[b];
return true;
}

//重载操作符
template<class E,class K>
ostream& operator<<(ostream& out,const HashTable<E,K>&x){
x.Output(out);
return out;
}

//输出该跳表的内容
template<class E,class K>
void HashTable<E,K>::Output(ostream& out)const
{
for(int i =0;i<D;i++){
if(!empty[i])
cout<<ht[i]<<" ";
else
cout<<"NULL"<<" ";
}
cout<<endl;
}

class BadInput{
public:
BadInput(){
cout<<"Bad Input!"<<endl;
}
};

class NoMem{
public:
NoMem(){
cout<<"No Memory!"<<endl;
}
};

//在散列表中插入
template<class E,class K>
HashTable<E,K>& HashTable<E,K>::Insert(const E&e){
K k = e;			//抽取key值
int b = hSearch(k);

//检查是否能完成插入
if(empty[b]){
empty[b]=false;
ht[b]=e;
return *this;
}
if (ht[b]==k)
throw BadInput();
throw NoMem();
}

int main(){
HashTable<float,int>myHash;
myHash.Insert(12);
myHash.Insert(23);
myHash.Insert(40);
myHash.Insert(22);

cout<<myHash<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: