本文参考了《数据结构与算法分析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;
}
部分运行结果截图: