hash_table.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iomanip>
#include <limits>
using namespace std;
namespace algo
{
template<typename T>
class UniversalHashTable
{
public:
UniversalHashTable()
{
_p = 101; //足够大的质数
_m = 10; //槽的个数
_items.resize(_m,NULL);
for(int i=0;i<_m;i++)
{
_items[i] = new _Node();
_items[i]->next = NULL;
}
_a = rand() % (_p - 1) + 1;
_b = rand() % _p;
}
~UniversalHashTable()
{
for(vector<_Node *>::iterator iter=_items.begin();iter!=_items.end();iter++)
{
while(*iter)
{
_Node *next = (*iter)->next;
delete *iter;
*iter = next;
}
}
}
void Insert(T &new_value)
{
_Node *new_item = new _Node();
new_item->item = new_value;
new_item->next = NULL;
int hash_value = _HashFunction(new_value);
new_item->next = _items[hash_value]->next;
_items[hash_value]->next = new_item;
}
bool Delete(T &delete_value)
{
int hash_value = _HashFunction(delete_value);
_Node *root = _items[hash_value];
while(root->next)
{
if(root->next->item == delete_value)
{
_Node *temp = root->next;
root->next = root->next->next;
delete temp;
return true;
}
else
{
root = root->next;
}
}
return false;
}
T* Search(T &search_value)
{
int hash_value = _HashFunction(search_value);
_Node *root = _items[hash_value]->next;
while(root)
{
if(root->item == search_value)
{
return &(root->item);
}
root = root->next;
}
return NULL;
}
void Display()
{
for(int i=0;i<_m;i++)
{
_Node *item = _items[i]->next;
cout << "槽" << setw(3) << i << setw(3);
while(item)
{
cout << "->" << item->item;
item = item->next;
}
cout << endl;
}
}
private:
struct _Node
{
T item;
_Node *next;
};
/// 全域散列函数
/// h(a,b,k) = ((a * k + b) mod p) mod m
int _HashFunction(T k)
{
return static_cast<int>(_a * k + _b) % _p % _m;
}
int _p,_m,_a,_b;
vector<_Node *> _items;
};
}
测试程序:
#include <iostream>
#include "hash_table.cpp"
using namespace std;
int main()
{
algo::UniversalHashTable<int> table;
cout << "添加内容[0,100)" << endl;
for(int i=0;i<100;i++)
{
table.Insert(i);
}
table.Display();
cout << "删除内容[10,50)" << endl;
for(int i=10;i<50;i++)
{
table.Delete(i);
}
table.Display();
for(int i=40;i<60;i++)
{
int *finded = table.Search(i);
cout << "检索节点" << i << ": ";
if(finded)
{
cout << *finded << endl;
}
else
{
cout << "未找到!" << endl;
}
}
return 0;
}
测试结果: