Question
Hashtable in C Please fix void ht_put(hashtable_t *ht, char *key, void *val) and void free_hashtable(hashtable_t *ht) Implement void ht_del(hashtable_t *ht, char *key) and void ht_rehash(hashtable_t
Hashtable in C
Please fix void ht_put(hashtable_t *ht, char *key, void *val) and void free_hashtable(hashtable_t *ht)
Implement void ht_del(hashtable_t *ht, char *key) and void ht_rehash(hashtable_t *ht, unsigned long newsize)
--------------[hashtable.h]---------------------------------------
-#########################################
#ifndef HASHTABLE_T
#define HASHTABLE_T
typedef struct hashtable hashtable_t;
typedef struct bucket bucket_t;
struct bucket {
char *key;
void *val;
bucket_t *next;
};
struct hashtable {
unsigned long size;
bucket_t **buckets;
};
unsigned long hash(char *str);
hashtable_t *make_hashtable(unsigned long size);
void ht_put(hashtable_t *ht, char *key, void *val);
void *ht_get(hashtable_t *ht, char *key);
void ht_del(hashtable_t *ht, char *key);
void ht_iter(hashtable_t *ht, int (*f)(char *, void *));
void ht_rehash(hashtable_t *ht, unsigned long newsize);
void free_hashtable(hashtable_t *ht);
#endif
-------------------------------------------------
----------------------[hashtable.c]--------------------------
--------------------------------------------------
##################################
#include
#include
#include "hashtable.h"
unsigned long hash(char *str) {
unsigned long hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
hashtable_t *make_hashtable(unsigned long size) {
hashtable_t *ht = malloc(sizeof(hashtable_t));
ht->size = size;
ht->buckets = calloc(sizeof(bucket_t *), size);
return ht;
}
void ht_put(hashtable_t *ht, char *key, void *val) {
/* FIXME: the current implementation doesn't update existing entries */
unsigned int idx = hash(key) % ht->size;
bucket_t *b = malloc(sizeof(bucket_t));
b->key = key;
b->val = val;
b->next = ht->buckets[idx];
ht->buckets[idx] = b;
}
void *ht_get(hashtable_t *ht, char *key) {
unsigned int idx = hash(key) % ht->size;
bucket_t *b = ht->buckets[idx];
while (b) {
if (strcmp(b->key, key) == 0) {
return b->val;
}
b = b->next;
}
return NULL;
}
void ht_iter(hashtable_t *ht, int (*f)(char *, void *)) {
bucket_t *b;
unsigned long i;
for (i=0; isize; i++) {
b = ht->buckets[i];
while (b) {
if (!f(b->key, b->val)) {
return ; // abort iteration
}
b = b->next;
}
}
}
void free_hashtable(hashtable_t *ht) {
free(ht); // FIXME: must free all substructures!
}
/* TODO */
void ht_del(hashtable_t *ht, char *key) {
}
void ht_rehash(hashtable_t *ht, unsigned long newsize) {
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started