I'd like to get feedback on whether my hash table is correct or not. Also, any ideas on performance?
template<class J,class K>
class List {
private:
struct Node {
J key;K data;
Node * next;
Node(J _key,K _data):key(_key),data(_data),next(nullptr) {}
}*head;
public:
List():head(nullptr){}
~List() {
deleteNode();
}
void insert(J _key ,K _data) {
Node * newNode = new Node(_key, _data);
newNode->next = head;
head = newNode;
}
void traverse() {
for(Node * curr = head; curr != nullptr; curr = curr->next) {
cout<< "( "<<curr->key << ", " << curr->data << " )" << " ";
}
}
K search(J key) {
if (!empty()){
for(Node * curr = head;curr != nullptr;curr = curr->next) {
if (curr->key == key) {
return curr->data;
}
}
}
return K(-1);
}
bool empty() { return (head == nullptr); }
void deleteNode() {
Node * tmp = nullptr;
for(Node * curr = head; curr != nullptr;){
tmp = curr->next;
delete curr;
curr = tmp;
}
}
};
template<class KEY, class VALUE>
class myHash {
private:
struct bucket {
List<KEY,VALUE> list_at_bucket;
}*Buckets;
int tableSize;
public:
myHash(int size) {
tableSize = size;
Buckets = new bucket[tableSize];
}
~myHash() {
for(int i = 0; i < tableSize; i++) {
Buckets[i].list_at_bucket.deleteNode();
}
}
void put(KEY k, VALUE value) {
int getCode = hash(k);
Buckets[getCode].list_at_bucket.insert(k,value);
}
VALUE getValue(KEY _key) {
int getCode = hash(_key);
return Buckets[getCode].list_at_bucket.search(_key);
}
bool contains(KEY _key) {
int getCode = hash(_key);
if (Buckets[getCode].list_at_bucket.search(_key) != -1) {
return true;
}
return false;
}
// need a template hash function
int hash(KEY key) const {
int value = 0;
for (char each: key) {
value += each;
}
return value % tableSize;
}
void traverse() {
for (int index = 0; index <tableSize; index++){
cout<< "[" << index << " ]-> ";
Buckets[index].list_at_bucket.traverse();
}
}
};