Created
August 29, 2017 16:50
-
-
Save md2perpe/e653cb4a0cad8169d33655a77e11c272 to your computer and use it in GitHub Desktop.
Combined hash and list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
#include <string.h> | |
#define SIZE 256 | |
struct element { | |
char *key; | |
double value; | |
struct element *bucket_next; | |
struct element *list_next; | |
}; | |
struct bucket { | |
struct element *first; | |
struct element *last; | |
}; | |
struct bucket hashtable[SIZE]; | |
struct element *list_last; | |
struct element *list_first; | |
int hash(char *key) { | |
int h = 0; | |
if (key) { | |
if (key[0]) { | |
h ^= key[0]; | |
} | |
} | |
return h; | |
} | |
void insert(char *key, double value) { | |
struct element *e = malloc(sizeof(struct element)); | |
e->key = key; | |
e->value = value; | |
e->bucket_next = 0; | |
e->list_next = 0; | |
// Add element to list | |
if (! list_first) | |
list_first = e; | |
if (list_last) | |
list_last->list_next = e; | |
list_last = e; | |
// Add element to hashtable | |
int h = hash(key); | |
if (! hashtable[h].first) { | |
hashtable[h].first = e; | |
hashtable[h].last = e; | |
} else { | |
hashtable[h].last->bucket_next = e; | |
hashtable[h].last = e; | |
} | |
} | |
void print_all() { | |
struct element *p; | |
for (p = list_first; p; p = p->list_next) { | |
printf("%s => %f\n", p->key, p->value); | |
} | |
} | |
int find(char *key, double *value) { | |
int h = hash(key); | |
struct element *e; | |
for (e = hashtable[h].first; e; e = e->bucket_next) { | |
if (0 == strcmp(key, e->key)) { | |
*value = e->value; | |
return 1; | |
} | |
} | |
return 0; | |
} | |
void check_for(char *key) { | |
double value; | |
if (find(key, &value)) { | |
printf("Found '%s' with value %f\n", key, value); | |
} else { | |
printf("Did not find value of '%s'\n", key); | |
} | |
} | |
init() { | |
int i; | |
for (i=0; i<SIZE; i++) { | |
hashtable[i].first = hashtable[i].last = 0; | |
} | |
list_first = list_last = 0; | |
} | |
main() { | |
init(); | |
insert("pi", 3.14159265); | |
insert("e", 2.718281828); | |
insert("gamma", 0.577215664901); | |
print_all(); | |
check_for("pi"); | |
check_for("psi"); | |
check_for("e"); | |
check_for("f"); | |
check_for("gamma"); | |
check_for("beta"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment