public
Created

  • Download Gist
gistfile1.txt
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#include "hashtable.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
 
void
hashtable_error(char* msg) {
puts(msg);
}
 
hashtable*
hashtable_create(unsigned int size) {
if (0 == size) {
hashtable_error("size must be positive");
return 0;
}
hashtable* retval = malloc(sizeof(hashtable));
retval->array = calloc(size, sizeof(hashtable_list_item));
retval->size = size;
return retval;
}
 
unsigned int
hash_pow(unsigned int base, unsigned int exponent) {
unsigned int i;
unsigned int retval = 1;
for (i=0; i<exponent; i++) {
retval *= base;
}
return retval;
}
 
unsigned int
hash(char* s, unsigned int modulus) {
unsigned int code = 0;
unsigned int i;
int len = strlen(s);
for(i=0; i<len; i++) {
code += s[i] * hash_pow(256, i);
}
return code % modulus;
}
 
void
hashtable_insert(hashtable* ht, char* key, char* value) {
if (0 == ht) {
hashtable_error("first argument is null");
return;
}
unsigned int slot;
slot = hash(key, ht->size);
hashtable_list_item* new_item = malloc(sizeof(hashtable_list_item));
new_item->key = key;
new_item->value = value;
new_item->next = ht->array[slot];
ht->array[slot] = new_item;
}
 
char*
hashtable_search(hashtable* ht, char* key) {
unsigned int slot;
slot = hash(key, ht->size);
hashtable_list_item* hli;
hli = ht->array[slot];
while (0 != hli) {
if (0 == strcmp(hli->key, key)) {
return hli->value;
}
hli = hli->next;
}
return 0;
}
 
void
hashtable_delete(hashtable* ht, char* key) {
unsigned int slot;
slot = hash(key, ht->size);
hashtable_list_item **hlip;
hlip = &(ht->array[slot]);
while ( *hlip ) {
if (0 == strcmp((*hlip)->key, key)) {
(*hlip) = (*hlip)->next;
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.