C++泛型编程实现哈希表(开散列法)

代码如下:

#include 
#include 
using namespace std;

template<typename K>
struct HashNode
{
     
	typedef HashNode<K> Node;

	K _val;
	Node * _next;

	HashNode(const K & val):_val(val),_next(nullptr){
     }
};

template<typename K>
class HashTable
{
     
public:
	typedef HashNode<K> Node;

	HashTable(int n = 10):_ht(10),_size(0){
     }

	bool insert(const K & val)
	{
     
		checkCapacity();

		int idx = val % _ht.size();

		Node *cur = _ht[idx];
		while (cur)
		{
     
			if (cur->_val == val) return false;
			cur = cur->_next;
		}

		cur = new Node(val);
		cur->_next = _ht[idx];
		_ht[idx] = cur;
		++_size;
		return true;
	}

	void checkCapacity()
	{
     
		if (_size == _ht.size())
		{
     
			int newC = _size == 0 ? 10 : 2 * _size;

			vector<Node *> newHt(newC);

			for (size_t i = 0; i < _ht.size(); i++)
			{
     
				Node *cur = _ht[i];
				while (cur)
				{
     
					Node *next = cur->_next;

					int idx = cur->_val % newHt.size();

					cur->_next = newHt[idx];
					newHt[idx] = cur;

					cur = next;
				}

				_ht[i] = nullptr;
			}

			swap(_ht, newHt);
		}
	}

	Node *find(const K & val)
	{
     
		int idx = val % _ht.size();
		Node *cur = _ht[idx];
		while (cur)
		{
     
			if (cur->_val == val) return cur;
			cur = cur->_next;
		}
		return nullptr;
	}

	bool erase(const K & val)
	{
     
		Node *node = find(val);
		if (node)
		{
     
			int idx = val % _ht.size();
			Node *cur = _ht[idx];
			Node *prev = nullptr;
			while (cur != node)
			{
     
				prev = cur;
				cur = cur->_next;
			}
			Node *next = cur->_next;
			if (prev) prev->_next = next;
			else _ht[idx] = next;

			--_size;
			delete node;
			return true;
		}
		return false;
	}

private:
	vector<Node *> _ht;
	int _size;
};

int main()
{
     
	HashTable<int> h;
	h.insert(12321);
	h.insert(131);
	h.insert(123);
	cout << h.find(131)->_val << endl;
	return 0;
}

测试结果:
C++泛型编程实现哈希表(开散列法)_第1张图片

你可能感兴趣的:(数据结构和算法,C++,哈希表,hash,查找,数据结构)