散列——分离链接法

来自《数据结构与算法 王立柱》

//HashTable.h
#include<list>
#include<vector>
#include<iomanip>
#include<algorithm>
using namespace std;
template<class Iterator,class T>
Iterator Find(Iterator first,Iterator last,const T& x)
{
	while(first!=last&&*first!=x)
	{
		++first;
	}
	return first;
}
template<class T>
class HashTable
{
	private:
		int nt;
		vector<list<T> > ht;
		int size;
		int (*hf)(const T&x );
	public:
		explicit HashTable(int n,int (*hash)(const T& x)):nt(n),hf(hash),size(0){ht.resize(n);}
		bool Insert(const T& x);
		bool Remove(const T& x);
		bool Find(const T& x)const;
		int Size(void)const{return size;}
		int Empty(void) const{return size==0;}
		int NumberOfBucket(void)const{return nt;}
		friend ostream& operator<<(ostream &ostr,const HashTable &ht)
		{
			int n=ht.NumberOfBucket();
			list<T>::const_iterator first,last;
			for(int i=0;i<n;i++)
			{
				first=ht.ht[i].begin(),last=ht.ht[i].end();
				for(;first!=last;first++)
				cout<<setw(4)<<*first<<' ';
				cout<<endl;
			}
			return ostr;
		}
};
template<class T>
bool HashTable<T>::Insert(const T&x)
{
	list<T> &L=ht[hf(x)];
	if(find(L.begin(),L.end(),x)!=L.end())
	{
		return 0;
	}
	L.push_back(x);
	size++;
	return 1;
}
template<class T>
bool HashTable<T>::Remove(const T&x)
{
	list<T> & L=ht[hf(x)];
	list<T>::iterator itr=find(L.begin(),L.end(),x);
	if(itr==L.end())
	{
		return 0;
	}
	L.erase(itr);
	size--;
	return 0;
}
template<class T>
bool HashTable<T>::Find(const T&x)const
{
	const list<T> &L=ht[hf(x)];
	if(find(L.begin(),L.end(),x)!=L.end())
	{
		return 1;
	}

	return 0;
}
//main.cpp
#include<iostream>
#include"HashTable.h"
using namespace std;
int hf(const int &key)
{
	return key%7;
}
int main()
{
	HashTable<int> HT(7,hf);
	for(int i=0;i<=27;i++)
	{
		HT.Insert(i);
	}
	cout<<HT<<endl;
	cout<<"after moving :"<<endl;
	if(HT.Find(20))
		HT.Remove(20);
	cout<<HT<<endl;
	return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值