笔者采用链表+数组的方式简单实现哈希表如下:
映射函数采用mod,哈希冲突解决使用链地址法
struct Node
{
int key;
Node* next;
Node() :key(-1),next(nullptr) {};
Node(int _key) :key(_key), next(nullptr) {};
};
class MyHashSet {
vector<Node*>HashList;
int base;
public:
MyHashSet() :base(769){
HashList.resize(base,new Node(-1));
}
void add(int key) {
Node* p = hash(key);
if(p->next == nullptr)
{
p->next = new Node(key);
}
}
void remove(int key) {
Node* p = hash(key);
if (p->next != nullptr)
{
Node* pNext = p->next;
p->next = pNext->next;
delete pNext;
}
}
bool contains(int key) {
Node* p = hash(key);
if (p->next == nullptr)
return false;
else
return true;
}
Node* hash(int key)
{
Node* p = HashList[key % base];
while (p->next != nullptr && p->next->key != key)
p = p->next;
return p;
}
};