分离链表法哈希表的C++实现(最新修改)

本文参考了《数据结构与算法分析C++描述(第3版)》[美] Mark Weiss 著       张怀勇 等译     刘田   审校

#include "stdafx.h"
#include<list>  
#include<vector>  
#include<iostream>

using namespace std;  
template <typename T>  
class HashTable  
{  
private:  
	vector<list<T> > theLists;  
	int myhash(T x)//对不同类型的数据可以用不同的hash函数  
	{  
		return hash(x);  
	}  

	int hash(int x)//对int类型的hash函数,在这里hash函数为简单的取余函数  
	{  
		return x % theLists.size();  
	}  
public:  
	HashTable(int s = 11){//构造函数,默认初始链表数为11  
		theLists.resize(s);  
	}  

	~HashTable()//析构函数 
	{ 
		makeEmpty();  
	}  

	void makeEmpty()//清空所有链表
	{  
		for(int i = 0;i < theLists.size();i++)  
			theLists.at(i).clear();  
	}  

	bool contain(T x)//查找元素
	{  
		list<int> ali=theLists.at(myhash(x));  
		list<int>::iterator ir=ali.begin();  
		for(;ir != ali.end();ir++){  
			if (*ir == x)  
				return true;  
		}  
		return false;  
	}

	void remove(T x)//删除元素  
	{
		list<int>*ali=&theLists.at(myhash(x));  
		list<int>::iterator ir=ali->begin();  
		for(;ir!=ali->end();ir++)
		{  
			if(*ir == x)
			{  
				ir=ali->erase(ir);  
			}  
		}  
	}  

	void insert(T x)//插入元素
	{  
		theLists.at(myhash(x)).push_back(x);  
	}  

	void print()//显示哈希表的元素结构
	{  
		for(int i=0;i<theLists.size();i++){  
			cout<<"第"<<i<<"条链表:";  
			if(theLists.at(i).empty())  
				cout<<"(empty)"<<endl;  
			else{  
				list<int>::iterator ir=theLists.at(i).begin();  
				cout << "[ " << *ir++;  
				while( ir != theLists.at(i).end())  
					cout << ", " << *ir++;  
				cout << " ]" << endl;  
			}  
		}  
	} 

	void rehash()//再散列  
	{  
		vector<list<T> > oldLists=theLists;  
		theLists.resize(2 * theLists.size() + 1);  
		for(int j =0;j<theLists.size();j++)  
			theLists[j].clear();  
		for(int i =0; i<oldLists.size( );i++)  
		{  
			list<T>::iterator itr=oldLists[i].begin();  
			while(itr!=oldLists[i].end())  
			{  
				insert(*itr);  
				itr++;  
			}  
		}  
	}  
};  

int _tmain(int argc, _TCHAR* argv[])
{
	HashTable<int> ha;  
	for(int j = 0;j <= 100;j++)
	{  
		ha.insert(j*j);
	}  
	ha.print();  
	if(ha.contain(400))
	{
		cout<<"有"<<endl;  
	}
	ha.remove(400);  
	if(ha.contain(400))
	{
		cout<<"有"<<endl; 
	}
	else
	{
		cout<<"无"<<endl;  
	}
	cout<<endl;  
	ha.print();  
	ha.rehash();  
	cout<<"再散列"<<endl;  
	ha.print();  
	return 0;  
}


部分运行结果截图:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值