#ifndef HASHTABLE_H #define HASHTABLE_H #include const int N = 10; template struct List { std::string key; K data; List* next; List(std::string key, K data) { this->key = key; this->data = data; next = nullptr; } }; template class HashTable { public: HashTable(); HashTable(const HashTable&) = delete; HashTable& operator=(const HashTable&) = delete; ~HashTable(); void Put(std::string key, K data); //add element K Get(std::string key); //search for element void Remove(std::string key); //remove element private: List** hashTable; unsigned HashFunction(std::string key); List* CheckKeyUniqueness(std::string key, int index); }; #endif // !HASHTABLE_H template HashTable::HashTable() { hashTable = new List*[N]; for (int i = 0; i < N; i++) hashTable[i] = nullptr; } template HashTable::~HashTable() { for (int i = 0; i < N; i++) { List* current = hashTable[i]; while (current != nullptr) { List* next = current->next; delete current; current = next; } } delete hashTable; } template void HashTable::Put(std::string key, K data) { unsigned result = HashFunction(key); if (CheckKeyUniqueness(key, result) != nullptr) return; List* newList = new List(key, data); newList->next = hashTable[result]; hashTable[result] = newList; } template K HashTable::Get(std::string key) { unsigned result = HashFunction(key); List* iter = hashTable[result]; while (iter->key != key) iter = iter->next; if (iter != nullptr) return iter->data; else throw std::logic_error("Can't find this element.\n"); } template void HashTable::Remove(std::string key) { unsigned result = HashFunction(key); List* iter = hashTable[result]; List* prev = iter; if (iter == hashTable[result] && iter->key == key) { hashTable[result] = iter->next; delete iter; return; } while (iter->key != key) { prev = iter; iter = iter->next; } prev->next = iter->next; delete iter; } template unsigned HashTable::HashFunction(std::string key) { int keyLength = key.length(); int result = keyLength; for (int i = 0; i < keyLength; i++) result = (result << 4) ^ (result >> 8) ^ (key[i]); return result % N; } template List* HashTable::CheckKeyUniqueness(std::string key, int index) { List* iter = hashTable[index]; while (iter != nullptr) { if (iter->key == key) return iter; iter = iter->next; } return nullptr; }