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

#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值