#include "hashtable.h" #define DEBUG 1 Hashtable::Hashtable() { for(int i = 0; i < TABLE_SIZE; i++) table[i] = 0; } //Hash Function: sum of the ASCII codes of the characters % TABLE_SIZE int Hashtable::hash (char *l) { int long sum = 0; int len = strlen(l); for(int i = 0; i < len; i++) sum += l[i]; return sum % TABLE_SIZE; } bool Hashtable::insert (Type* new_item) { int index; List* list; Node* p; index = hash(new_item->get_key()); if(DEBUG) cout << endl << "The index given by a hashfunction is " << index << endl; if(table[index] == 0){ table[index] = new List(*new_item); return true; } else { list = table[index]; p = list->finditem(*new_item); if(p == NULL) list->insert(*new_item); else p->setinfo(*new_item); return true; } return false; //should never get here } void Hashtable::view() { for(int i = 0; i < TABLE_SIZE; i++) { if(table[i] != 0 ){ List list = *table[i]; ListIter iter(list); while(!iter.done()) { if(strcmp(iter.value().get_key(), "*") != 0) cout << "Index: " << i << iter.value(); iter.next(); } } } } Type* Hashtable::find (char* key) { int index, new_index; Type *item; List *list; Node *p; item = new Type(key); new_index = index = hash(key); if (table[index] == 0) return 0; list = table[index]; p = list->finditem(*item); if(p == NULL) return NULL; else { *item = p->getinfo(); return item; } } bool Hashtable::remove(char *key) { int index, new_index; List list; new_index = index = hash(key); if (table[index] == 0) return false; list = *table[index]; ListIter iter(list); while(!iter.done()) { Node *node = iter.lookup(); Type value = node->getinfo(); if (strcmp(value.get_key(), key) == 0) { value.set_key("*"); node->setinfo(value); return true; } iter.next(); } return false; }