Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions 05-methods/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,23 +84,26 @@ void ht_delete(ht_hash_table* ht, const char* key) {
if (strcmp(item->key, key) == 0) {
ht_del_item(item);
ht->items[index] = &HT_DELETED_ITEM;
ht->count--;
return;
}
}
index = ht_get_hash(key, ht->size, i);
item = ht->items[index];
i++;
}
ht->count--;
}
```
After deleting, we decrement the hash table's `count` attribute.

We also need to modify `ht_insert` and `ht_search` functions to take account of
We also need to modify `ht_insert`, `ht_search`, and `ht_del_hash_table` functions to take account of
deleted nodes.

When searching, we ignore and 'jump over' deleted nodes. When inserting, if we
hit a deleted node, we can insert the new node into the deleted slot.

When deleting the hash table, we need to make sure to not call free() on the HT_DELETED_ITEM pointers.

```c
// hash_table.c
void ht_insert(ht_hash_table* ht, const char* key, const char* value) {
Expand All @@ -124,6 +127,17 @@ char* ht_search(ht_hash_table* ht, const char* key) {
}
// ...
}

void ht_del_hash_table(ht_hash_table* ht) {
for (int i = 0; i < ht->size; i++) {
ht_item* item = ht->items[i];
if (item != NULL && item != &HT_DELETED_ITEM) {
ht_del_item(item);
}
}
free(ht->items);
free(ht);
}
```

## Update
Expand Down