#include <iostream>
#include <Windows.h>
#include <vector>
using namespace std;
const int TABLE_SIZE = 51;
template <typename T>
class LinkedHashEntry
{
private:
int key;
T value;
LinkedHashEntry<T> *next;
public:
LinkedHashEntry(int key, int value)
{
this->key = key;
this->value = value;
this->next = NULL;
}
int getKey()
{
return key;
}
T getValue()
{
return value;
}
void setValue(const T &value)
{
this->value = value;
}
LinkedHashEntry *getNext()
{
return next;
}
void setNext(LinkedHashEntry<T> *next)
{
this->next = next;
}
};
template <typename T>
class HashMap
{
private:
LinkedHashEntry<T> **table;
public:
HashMap()
{
table = new LinkedHashEntry<T>*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;
}
T get(int key)
{
int hash = (key % TABLE_SIZE);
if (table[hash] == NULL)
return -1;
else
{
LinkedHashEntry<T> *entry = table[hash];
while (entry != NULL && entry->getKey() != key)
entry = entry->getNext();
if (entry == NULL)
return -1;
else
return entry->getValue();
}
}
void put(int key, const T &value)
{
int hash = (key % TABLE_SIZE);
if (table[hash] == NULL)
table[hash] = new LinkedHashEntry<T>(key, value);
else
{
LinkedHashEntry<T> *entry = table[hash];
while (entry->getNext() != NULL && entry->getKey() != key)
entry = entry->getNext();
// exist entity with the same key value, so replace
// no same key value, insert
if (entry->getKey() == key)
entry->setValue(value);
else
entry->setNext(new LinkedHashEntry<T>(key, value));
}
}
void remove(int key)
{
int hash = (key % TABLE_SIZE);
if (table[hash] != NULL)
{
LinkedHashEntry<T> *prevEntry = NULL;
LinkedHashEntry<T> *entry = table[hash];
while (entry->getNext() != NULL && entry->getKey() != key)
{
prevEntry = entry;
entry = entry->getNext();
}
if (entry->getKey() == key)
{
if (prevEntry == NULL)
{
LinkedHashEntry<T> *nextEntry = entry->getNext();
delete entry;
table[hash] = nextEntry;
}
else
{
LinkedHashEntry<T> *next = entry->getNext();
delete entry;
prevEntry->setNext(next);
}
}
}
}
~HashMap() {
for (int i = 0; i < TABLE_SIZE; i++)
if (table[i] != NULL)
{
LinkedHashEntry<T> *prevEntry = NULL;
LinkedHashEntry<T> *entry = table[i];
while (entry != NULL)
{
prevEntry = entry;
entry = entry->getNext();
delete prevEntry;
}
}
delete[] table;
}
};
int main()
{
HashMap<int> hashtable;
hashtable.put(10, 100);
hashtable.put(61, 199);
hashtable.put(1, 10);
hashtable.put(52, 22);
cout << hashtable.get(1) << endl;
hashtable.put(1, 1001);
cout << hashtable.get(1) << endl;
hashtable.remove(1);
cout << hashtable.get(1) << endl;
system("PAUSE");
return 0;
}
The code is from:
http://www.algolist.net/Data_structures/Hash_table/Chaining
The top of chaining hash table is:
More proof and detail could be found at:
http://staff.ustc.edu.cn/~csli/graduate/algorithms/book6/chap12.htm