线性探测哈希表

//哈希闭散列线性探测
#include
#include
#include
using namespace std;
enum Status
{
EXIST,DEL,EMPTY
};
template <class K,class V>
struct HashNode
{
pair<K, V>_val;
Status _status;
HashNode(const pair<K, V>& val = pair<K, V>())
:_val(val)
,_status(EMPTY)
{}
};

template<class K,class V>
class HashTable
{
public:
HashTable(size_t n=10)
{
_table.resize(n);
_size = 0;
}
bool insert(const pair<K, V>& val)
{
checkCapacity();
int idx = val.first % _table.size();
if (_table[idx]._status == EXIST)
{
if (_table[idx]._val.first == val.first)
{
return false;
}
idx++;
if (idx == _table.size())
idx = 0;
}
_table[idx]._val = val;
_table[idx]._status = EXIST;
_size++;
return true;
}
void checkCapacity()
{
if ((_size * 10) / _table.size() >= 7)
{
HashTable<K, V>h(_table.size() * 2);
//旧元素入新表
for (int i = 0; i < _table.size(); i++)
{
if (_table[i]._status == EXIST)
{
h.insert(_table[i]._val);
}
}
swap(_table, h._table);
}
}
HashNode<K, V>* find(const K& key)
{
int idx = key % _table.size();
while (_table[idx]._status != EMPTY)
{
if (_table[idx]._status == EXIST)
{
if (_table[idx]._val.first == key)
{
return &_table[idx];
}
}
++idx;
if (idx == _table.size())
idx = 0;
}
return nullptr;
}
bool erase(const K& key)
{
HashNode<K, V>* p = find(key);
if §
{
p->_status = DEL;
_size–;
return true;
}
return false;
}
private:
vector<HashNode<K,V>>_table;
size_t _size;
};
int main()
{
HashTable<int, int>hash;
hash.insert(make_pair(1, 1));
hash.insert(make_pair(2, 2));
hash.insert(make_pair(3, 3));
hash.insert(make_pair(4, 4));
hash.insert(make_pair(5, 1));
hash.insert(make_pair(6, 1));
hash.insert(make_pair(7, 1));
hash.insert(make_pair(8, 1));
hash.insert(make_pair(9, 1));
hash.insert(make_pair(10, 1));
hash.insert(make_pair(11, 1));
hash.insert(make_pair(12, 1));
hash.insert(make_pair(13, 1));
cout << hash.erase(18) << hash.erase(13) << hash.erase(15) << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值