暂时不考虑扩容和其他的,先把最简单的实现
- 使用除留余数法计算桶号
- 检查桶内是否有相同元素
- 把元素头插到数组中
- 底层是一个数组,数组中存放的是相同地址的元素链表的首地址
#include<iostream>
#include<vector>
using namespace std;
template<typename T>
class HashNode
{
public:
HashNode(const T& data) :_data(data), _pNext(nullptr)
{
}
public:
HashNode<T>* _pNext;
T _data;
};
template<typename T>
class HashBucket
{
typedef HashNode<T> Node;
public:
HashBucket(int capacity = 10) : _size(0)
{
_hashtable.resize(capacity);
}
Node* Insert(const T& data)
{
size_t bucketNo = HashFunc(data);
Node* pCur = _hashtable[bucketNo];
while (pCur != nullptr)
{
if (pCur->_data == data)
{
return pCur;
}
pCur = pCur->_pNext;
}
pCur = new Node(data);
pCur->_pNext = _hashtable[bucketNo];
_hashtable[bucketNo] = pCur;
_size++;
return pCur;
}
void PrintData()
{
for (size_t i = 0; i < _hashtable.capacity(); ++i)
{
cout << "HashBucket[" << i << "]:";
Node* pCur = _hashtable[i];
while (pCur != nullptr)
{
cout << pCur->_data << " ";
pCur = pCur->_pNext;
}
cout << endl;
}
}
private:
int HashFunc(const T& data)
{
return data%_hashtable.capacity();
}
private:
size_t _size;
vector<Node*> _hashtable;
};
int main()
{
int array[] = { 8, 5, 9, 3, 7, 4, 6, 2, 1, 99, 87, 65 };
HashBucket<int> t;
for (auto e : array)
{
t.Insert(e);
}
t.PrintData();
system("pause");
return 0;
}