// Specification file for the Hash class // Written By: Iurii Tatishchev // Changed by: Iurii Tatishchev #ifndef HASHTABLE_H_ #define HASHTABLE_H_ #include "HashNode.h" template class HashTable { private: HashNode *hashAry; int hashSize; int count; public: HashTable() { count = 0; hashSize = 53; hashAry = new HashNode[hashSize]; } HashTable(int n) { count = 0; hashSize = n; hashAry = new HashNode[hashSize]; } ~HashTable() { delete[] hashAry; } int getCount() const { return count; } int getSize() const { return hashSize; } double getLoadFactor() const { return 100.0 * count / hashSize; } bool isEmpty() const { return count == 0; } bool isFull() const { return count == hashSize; } bool insert(const ItemType &itemIn, int h(const ItemType &key, int size)); bool remove(ItemType &itemOut, const ItemType &key, int h(const ItemType &key, int size)); int search(ItemType &itemOut, const ItemType &key, int h(const ItemType &key, int size)) const; }; /*~*~*~* Insert an item into the hash table It does not reject duplicates *~**/ template bool HashTable::insert(const ItemType &itemIn, int h(const ItemType &key, int size)) { if (count == hashSize) return false; int pos = h(itemIn, hashSize); int collisions = 0; while (hashAry[pos].getOccupied() == 1) { ++pos; ++collisions; pos = pos % hashSize; } hashAry[pos].setItem(itemIn); hashAry[pos].setOccupied(1); hashAry[pos].setNoCollisions(collisions); count++; return true; } /*~*~*~* Removes the item with the matching key from the hash table if found: - copies data in the hash node to itemOut - replaces data in the hash node with an empty record (occupied = -1: deleted!) - returns true if not found: - returns false *~**/ template bool HashTable::remove(ItemType &itemOut, const ItemType &key, int h(const ItemType &key, int size)) { int pos = h(key, hashSize); for (int collisions = 0; collisions < count; collisions++) { if (hashAry[pos].getOccupied() == 1 && hashAry[pos].getItem() == key) { itemOut = hashAry[pos].getItem(); // -1 means freed hashAry[pos].setOccupied(-1); count--; return true; } pos = (pos + 1) % hashSize; } return false; } /*~*~*~* hash search - linear probe if found: - copy data to itemOut - returns the number of collisions for this key if not found, returns -1 *~**/ template int HashTable::search(ItemType &itemOut, const ItemType &key, int h(const ItemType &key, int size)) const { int pos = h(key, hashSize); for (int collisions = 0; collisions < count; collisions++) { if (hashAry[pos].getOccupied() == 0) return -1; if (hashAry[pos].getOccupied() == 1 && hashAry[pos].getItem() == key) { itemOut = hashAry[pos].getItem(); return hashAry[pos].getNoCollisions(); } pos = (pos + 1) % hashSize; } return -1; } #endif // HASHTABLE_H_