C++泛型编程实现哈希表(开散列法)
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++泛型编程实现哈希表(开散列法)相关的知识,希望对你有一定的参考价值。
代码如下:
#include <iostream>
#include <vector>
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++泛型编程实现哈希表(开散列法)的主要内容,如果未能解决你的问题,请参考以下文章