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

数据结构 hashtable C++实现 链式

2015-03-07 00:00 435 查看
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <iterator>
bool isPrime(int x)
{
for(int i = 2; i * i <= x; ++i)
{
if(x % i == 0)
return false;
}
return true;
}
int nextprime(int x)
{
for(;;++x)
{
if(isPrime(x))
return x;
}
}
using namespace std;
template<class HashedObj>
class HashTable
{
public:
explicit HashTable(int size = 101);
bool contains(const HashedObj& x) const;
void makeEmpty();
bool insert(const HashedObj& x);
bool remove(const HashedObj& x);
void printtab() const;
private:
vector<list<HashedObj> > theLists;
int currentSize;
void rehash();
int myhash(const HashedObj& x) const;
int hash(const HashedObj& x) const;
};
template<class HashedObj>
HashTable<HashedObj>::HashTable(int size)
{
theLists.resize(size);
}
template<class HashedObj>
bool HashTable<HashedObj>::contains(const HashedObj& x) const
{
const list<HashedObj>& whichList = theLists[myhash(x)];
return find(whichList.begin(), whichList.end(), x) == whichList.end();
}
template<class HashedObj>
void HashTable<HashedObj>::makeEmpty()
{
for(size_t i = 0; i < theLists.size(); ++i)
theLists[i].clear();
}
template<class HashedObj>
bool HashTable<HashedObj>::insert(const HashedObj& x)
{
list<HashedObj> &whichList = theLists[myhash(x)];
if(find(whichList.begin(), whichList.end(), x) != whichList.end())
return false;
whichList.push_back(x);
if(++currentSize > theLists.size())
rehash();
return true;
}
template<class HashedObj>
bool HashTable<HashedObj>::remove(const HashedObj& x)
{
list<HashedObj> &whichList = theLists[myhash(x)];
typename::list<HashedObj>::iterator itr = find(whichList.begin(), whichList.end(), x);
if(itr == whichList.end())
return false;
whichList.erase(itr);
--currentSize;
return true;
}
template<class HashedObj>
void HashTable<HashedObj>::rehash()
{
vector<list<HashedObj> > oldLists = theLists;
theLists.resize(nextprime(2 * theLists.size()));
for(size_t j = 0; j < theLists.size(); ++j)
theLists[j].clear();
currentSize = 0;
for(size_t i = 0; i < oldLists.size(); ++i)
{
typename list<HashedObj>::iterator itr = oldLists[i].begin();
while(itr != oldLists[i].end())
insert(*itr++);
}
}
template<class HashedObj>
int HashTable<HashedObj>::myhash(const HashedObj& x) const
{
int hashval = hash(x);
hashval %= theLists.size();
if(hashval < 0)
hashval += theLists.size();
return hashval;
}
template<class HashedObj>
void HashTable<HashedObj>::printtab() const
{
for(size_t i = 0; i < theLists.size(); ++i)
{
copy(theLists[i].begin(), theLists[i].end(), ostream_iterator<HashedObj>(cout, " "));
if(!theLists[i].empty())
cout << endl;
}
}
template<>
int HashTable<int>::hash(const int& x) const
{
return x % theLists.size();
}

template<>
int HashTable<string>::hash(const string& x) const
{
return x[0] % theLists.size();
}
int main()
{
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: