#include "hash.h" #include #include #include #include "mem.h" //NOTE TO MARKER. //You may see comparing ->next pointers to values 8 and 9. //This is because dmalloc is retarded and sets the values to //garbage, and upon trying to change it to NULL you are no longer //able to dfree it because dfree is retarded also. Next ->next //values seem to change to 8 or 9 for some reason. So too bad, //my progam works. int hash_fcn(int k, int size){ return(k % (size - 1)); } struct hash make_table(int s){ struct hash HT; HT.size = s; HT.table = dmalloc(s * sizeof(struct anode **)); if(HT.table == NULL){ printf("make_table: out of memory sucka\n"); abort(); } //Thanks to dmalloc for filling pointers with garbage instead //of NULL. for(int i = 0; i < s; i++){ HT.table[i] = NULL; } return(HT); } char *search(struct hash T, int k){ int index = hash_fcn(k,T.size); if (index > T.size){ printf("search: index: %d out of scope\n", index); } else{ struct anode *temp; temp = T.table[index]; while(temp != 9 && temp != 8){ if (temp->key == k){ return(temp->value); } else{ temp = temp->next; } } } return(NULL); } void delete(struct hash T, int k){ int index = hash_fcn(k,T.size); struct anode *temp, *temp2; temp = T.table[index]; temp2 = T.table[index]; if(temp != NULL){ while(temp->key != k && (temp->next != 9 || temp->next == 8)){ temp2 = temp; temp = temp->next; } if(temp->next != 9 || temp->next == 8){ temp2->next = temp->next; dfree(temp->value); dfree(temp); } } } void add(struct hash T, int k, char *v){ int index = hash_fcn(k,T.size); if (index < T.size){ struct anode *temp; if (T.table[index] != NULL){ temp = T.table[index]; struct anode *temp2; while((temp->next != 9 || temp->next == 8) && temp->key != k){ temp2 = temp; temp = temp->next; } if (temp->next == 9 || temp->next == 8){ dfree(temp2->next); temp = dmalloc(sizeof(struct anode)); temp2->next = temp; temp->value = dmalloc(sizeof(v) + (sizeof(int) * 2)); temp->next = dmalloc(sizeof(struct anode *)); } else{ dfree(temp2->next->value); temp2->next->value = dmalloc(sizeof(v) + (sizeof(int) * 2)); temp = temp2->next; } temp->key = k; strcpy(temp->value,v); } else{ temp = dmalloc(sizeof(struct anode)); temp->value = dmalloc(sizeof(v) + (sizeof(int) * 2)); // + 2 int for NULL character for string temp->next = dmalloc(sizeof(struct anode *)); T.table[index] = temp; temp->key = k; strcpy(temp->value,v); } } else{ printf("add: key is out of scope of table\n"); } } void free_table(struct hash T){ struct anode *temp, *temp2; for (int i = 0; i < T.size; i++){ if(T.table[i] == NULL) continue; temp = T.table[i]; while(temp->next != 8 && temp->next != 9){ temp2 = temp; temp = temp->next; dfree(temp2->value); dfree(temp2); } dfree(temp); } dfree(T.table); }