-
Notifications
You must be signed in to change notification settings - Fork 1
/
htab_erase.c
49 lines (45 loc) · 1.21 KB
/
htab_erase.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
* Řešení IJC-DU2
* Autor: Tomáš Matuš, FIT VUT Brno
* Login: xmatus37
* Datum: 19.4.2021
* Přeloženo: gcc 10.2.0
*/
#include <stdlib.h>
#include "htab.h"
#include "htab_struct.h"
bool htab_erase(htab_t * t, htab_key_t key) {
size_t index = htab_hash_function(key) % t->arr_size;
struct htab_item *itm = t->arr[index];
if (itm == NULL) {
return false;
}
// compare keys with first item on index
if (strcmp(itm->pair.key, key) == 0) {
// keys match
t->arr[index] = itm->next;
itm->next = NULL;
free((char*)itm->pair.key);
free(itm);
t->size--;
return true;
} else {
// run through linked list and search for key
struct htab_item *prev = itm;
for (; itm->next != NULL; itm = itm->next) {
// compare keys
if (strcmp(itm->pair.key, key) == 0) {
// key in list matches
prev->next = itm->next;
itm->next = NULL;
free((char*)itm->pair.key);
free(itm);
t->size--;
return true;
}
prev = itm;
}
}
// key not found
return false;
}