#include <iostream>
using namespace std;
template<typename KeyType,typename ValueType>
class HashNode
{
public:
KeyType key;
ValueType value;
HashNode* next;
HashNode(const KeyType& key, const ValueType& value)
{
this->key = key;
this->value = value;
this->next = nullptr;
}
};
template<typename KeyType, typename ValueType>
class HashTable
{
private:
int size;
HashNode<KeyType, ValueType>** table;
int hash(const KeyType& key)const
{
int hashkey = key % size;
if (hashkey < 0)
{
hashkey += size;
}
return hashkey;
}
public:
HashTable(int size = 256);
~HashTable();
void insert(const KeyType& key, const ValueType& value);
void remove(const KeyType& key);
bool find(const KeyType& key, ValueType& value)const;
};
template<typename KeyType, typename ValueType>
HashTable<KeyType, ValueType>::HashTable(int size)
{
this->size = size;
this->table = new HashNode<KeyType, ValueType>*[size];
for (int i = 0; i < size; i++)
{
table[i] = nullptr;
}
}
template<typename KeyType, typename ValueType>
HashTable<KeyType, ValueType>::~HashTable()
{
for (int i = 0; i < size; i++)
{
if (table[i])
{
HashNode<KeyType, ValueType>* cur = table[i];
while (cur)
{
HashNode<KeyType, ValueType>* next = cur->next;
delete[] cur;
cur = next;
}
table[i] = nullptr;
}
}
delete table;
table = NULL;
}
template<typename KeyType, typename ValueType>
void HashTable<KeyType, ValueType>::insert(const KeyType& key, const ValueType& value)
{
int index = hash(key);
HashNode<KeyType, ValueType>* now = new HashNode<KeyType, ValueType>(key, value);
if (table[index] == nullptr)
{
table[index] = now;
}
else
{
now->next = table[index];
table[index] = now;
}
}
template<typename KeyType, typename ValueType>
void HashTable<KeyType, ValueType>::remove(const KeyType& key)
{
int index = hash(key);
if (table[index])
{
if (table[index]->key == key)
{
HashNode<KeyType, ValueType>* next = table[index]->next;
delete[] table[index];
table[index] = next;
}
else
{
HashNode<KeyType, ValueType>* cur = table[index];
while (cur->next&&cur->next->key!=key)
{
cur = cur->next;
}
if (cur->next)
{
HashNode<KeyType, ValueType>* next = cur->next->next;
delete[] cur->next;
cur->next = next;
}
}
}
}
template<typename KeyType, typename ValueType>
bool HashTable<KeyType, ValueType>::find(const KeyType& key, ValueType& value)const
{
int index = hash(key);
if (table[index])
{
if (table[index]->key == key)
{
value = table[index]->value;
return true;
}
else
{
HashNode<KeyType, ValueType>* cur = table[index];
while (cur->next && cur->next->key != key)
{
cur = cur->next;
}
if (cur->next)
{
value = cur->next->value;
return true;
}
}
}
return false;
}
哈希表C++实现
最新推荐文章于 2024-07-19 19:11:19 发布