From 0431f5b485b8542015912b87b439b807db9cefa2 Mon Sep 17 00:00:00 2001 From: Durgesh kumar prajapati <98798977+Durgesh4993@users.noreply.github.com> Date: Tue, 11 Oct 2022 13:00:16 +0530 Subject: [PATCH] Create Hash map in cpp --- Hash map in cpp | 92 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Hash map in cpp diff --git a/Hash map in cpp b/Hash map in cpp new file mode 100644 index 0000000..7ed2c5e --- /dev/null +++ b/Hash map in cpp @@ -0,0 +1,92 @@ +// Hash map class template +template > +class HashMap { +public: + HashMap() { + // construct zero initialized hash table of size + table = new HashNode *[TABLE_SIZE](); + } + + ~HashMap() { + // destroy all buckets one by one + for (int i = 0; i < TABLE_SIZE; ++i) { + HashNode *entry = table[i]; + while (entry != NULL) { + HashNode *prev = entry; + entry = entry->getNext(); + delete prev; + } + table[i] = NULL; + } + // destroy the hash table + delete [] table; + } + + bool get(const K &key, V &value) { + unsigned long hashValue = hashFunc(key); + HashNode *entry = table[hashValue]; + + while (entry != NULL) { + if (entry->getKey() == key) { + value = entry->getValue(); + return true; + } + entry = entry->getNext(); + } + return false; + } + + void put(const K &key, const V &value) { + unsigned long hashValue = hashFunc(key); + HashNode *prev = NULL; + HashNode *entry = table[hashValue]; + + while (entry != NULL && entry->getKey() != key) { + prev = entry; + entry = entry->getNext(); + } + + if (entry == NULL) { + entry = new HashNode(key, value); + if (prev == NULL) { + // insert as first bucket + table[hashValue] = entry; + } else { + prev->setNext(entry); + } + } else { + // just update the value + entry->setValue(value); + } + } + + void remove(const K &key) { + unsigned long hashValue = hashFunc(key); + HashNode *prev = NULL; + HashNode *entry = table[hashValue]; + + while (entry != NULL && entry->getKey() != key) { + prev = entry; + entry = entry->getNext(); + } + + if (entry == NULL) { + // key not found + return; + } + else { + if (prev == NULL) { + // remove first bucket of the list + table[hashValue] = entry->getNext(); + } else { + prev->setNext(entry->getNext()); + } + delete entry; + } + } + +private: + // hash table + HashNode **table; + F hashFunc; +};