-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtab_erase.c
53 lines (44 loc) · 1.15 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
50
51
52
53
/**
* @file htab_init.c
* @author Samuel Stolarik (xstola03)
* @brief 2nd part of DU2 IJC
*
* @date 2022-04-10
*
*/
#include "htab.h"
#include "p_htab.h"
#include <stdbool.h>
bool htab_erase(htab_t * t, htab_key_t key)
{
if (t -> arr_size == 0){
return false;
}
size_t index = htab_hash_function(key) % t -> arr_size;
htab_item_t * cur = t -> ptr[index];
htab_item_t * prev = NULL;
bool deleted = false;
while (cur != NULL)
{
if (strcmp(key, cur -> pair.key) == 0){
htab_item_t * tmp = cur -> next;
free((void *) cur -> pair.key);
free(cur);
if (prev == NULL){ //in case the deleted item was the first item in the list
t -> ptr[index] = tmp;
}
else {
prev -> next = tmp;
}
t -> size -= 1; //number of pairs in the htab
deleted = true;
break;
}
prev = cur;
cur = cur -> next;
}
if (t -> size == 0 || t -> size / t -> arr_size < AVG_LEN_MIN){
htab_resize(t, t -> arr_size / 2);
}
return deleted;
}