一个简单的哈希表的实现

//
// 用连地址表示的哈希表
//
#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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值