//
// 用连地址表示的哈希表
//
#include <iostream>
using namespace std;
template <typename T>
class Node
{
public:
Node(T val = 0) : key(val), next(NULL), val(88)
{
// 为什么这里的赋值通过offset宏看不到,看到的只是初始化列表里的88
val = 33;
}
int val;
Node * next;
T key;
};
template <typename T>
class HashTable
{
public:
// 建立一个哈希表要指定大小和哈希函数
HashTable(int size, int (*hashFunc)(const T &)) : m_size(size), m_hashFunc(hashFunc)
{
m_ht = new Node<T> * [m_size];
for(int i = 0; i < m_size; ++i)
m_ht[i] = NULL;
}
~HashTable()
{
for(int i = 0; i < m_size; ++i)
{
Node<T> *p = m_ht[i];
while(p != NULL)
{
Node<T> * cur = p;
p = p->next;
delete cur;
}
}
delete m_ht;
}
T * Find(const T & x);
void Insert(const T & x);
private:
int m_size;
Node<T> ** m_ht; // hash table
int (*m_hashFunc)(const T &);
};
// 查找
template <typename T>
T * HashTable<T>::Find(const T & x)
{
int pos = m_hashFunc(x);
Node<T> * p = m_ht[pos];
while(p != NULL)
{
if(p->key == x)
return &p->key;
p = p->next;
}
return NULL;
}
// 插入
template <typename T>
void HashTable<T>::Insert(const T & x)
{
int pos = m_hashFunc(x);
Node<T> ** p = &m_ht[pos];
while(*p != NULL)
p = &((*p)->next);
*p = new Node<T>(x);
}
/
// 哈希函数,保正哈希值均匀的落在哈希表的空间内
/
int HashFunc(const int & x)
{
return x % 10;
}
#define MEMOFF(struc, e) (size_t)&(((struc*)0)->e)
int main()
{
HashTable<int> ht(10, HashFunc);
ht.Insert(1);
ht.Insert(2);
ht.Insert(3);
int* res = ht.Find(3);
if (res != NULL)
{
cout << *res << endl;
size_t offset = MEMOFF(Node<int>, key);
Node<int> *s = (Node<int>*)((size_t)res - offset);
cout << s->val << endl;
}
else
cout << "not found" << endl;
return 0;
}
一个简单的哈希表的实现
最新推荐文章于 2021-12-26 21:09:09 发布