Hash Tables

Contents

Problems

Problem : Augmenting our current implementation of the hash table, write a delete function to remove a string from the hash table.

```
int delete_string(hash_table_t *hashtable, char *str)
{
int i;
list_t *list, *prev;
unsigned int hashval = hash(str);

/* find the string in the table keeping track of the list item
* that points to it
*/
for(prev=NULL, list=hashtable->table[hashval];
list != NULL && strcmp(str, list->str);
prev = list,
list = list->next);

/* if it wasn't found, return 1 as an error */
if (list==NULL) return 1; /* string does not exist in table */

/* otherwise, it exists. remove it from the table */
if (prev==NULL) hashtable[hashval] = list->next;
else prev->next = list->next;

/* free the memory associate with it */
free(list->str);
free(list);

return 0;
}
```

Problem : To augment our current implementation, write a function that counts the number of strings stored in the hash table.

```
int count_strings(hash_table_t *hashtable)
{
int i, count = 0;
list_t *list;

/* error check to make sure hashtable exists */
if (hashtable==NULL) return -1;

/* go through every index and count all list elements in each index */
for(i=0; i<hashtable->size; i) {
for(list=hashtable[i]; list != NULL; list = list->next) count;
}

return count;
}
```

Problem : How would we augment our hash table such that it stores information on students? We'd still like to look up a student's name to find them, but we'd then immediately have access to information about them, such as a letter grade, their graduation year, etc.

All we'd have to do is modify the linked list structure to include all that information:
```
typedef struct _list_t_ {
char *name; /* and of course we'd have to change our code to use name */