going through an example of hash table
This commit is contained in:
parent
fb08343f8c
commit
2cc09b147c
|
@ -0,0 +1,37 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct item {
|
||||
char *key;
|
||||
int value;
|
||||
} item;
|
||||
|
||||
item *linear_search(item *items, size_t size, const char *key) {
|
||||
for (size_t i = 0; i < size; i++) {
|
||||
if (strcmp(items[i].key, key) == 0) {
|
||||
return (&items[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return (NULL);
|
||||
}
|
||||
|
||||
int main() {
|
||||
item items[] = {
|
||||
{"foo", 10},
|
||||
{"bar", 20},
|
||||
{"hello", 30},
|
||||
{"x", 40}};
|
||||
|
||||
size_t total_items = sizeof(items) / sizeof(items);
|
||||
|
||||
item *found = linear_search(items, total_items, "foo");
|
||||
|
||||
if (found == NULL) {
|
||||
printf("linear search: value of 'foo' has no key\n");
|
||||
return (1);
|
||||
}
|
||||
|
||||
printf("linear search: value of 'foo' is: %d", found->value);
|
||||
return (0);
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct HashTable {
|
||||
char *data[16];
|
||||
} HashTable;
|
||||
|
||||
HashTable *new_hashtable() {
|
||||
HashTable *ht = malloc(sizeof(HashTable));
|
||||
for (int i = 0; i < 16; i++) {
|
||||
ht->data[i] = NULL;
|
||||
}
|
||||
|
||||
return (ht);
|
||||
}
|
||||
|
||||
int get_index_for_letter(char letter) {
|
||||
if (letter >= 'a' && letter <= 'z') {
|
||||
return (letter - 'a') + 1;
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
int hash(char *word) {
|
||||
int word_len = strlen(word);
|
||||
int accum = 1;
|
||||
int index;
|
||||
for (int i = 0; i < word_len; i++) {
|
||||
index = get_index_for_letter(word[i]);
|
||||
accum *= index;
|
||||
}
|
||||
|
||||
return accum % 16;
|
||||
}
|
||||
|
||||
char *get(HashTable *h, char *key) {
|
||||
int hash_val = hash(key);
|
||||
return h->data[hash_val];
|
||||
}
|
||||
|
||||
void insert(HashTable *h, char *key, char *value) {
|
||||
int hashed_key = hash(key);
|
||||
|
||||
if (h->data[hashed_key] != NULL) {
|
||||
fprintf(stderr, "ERROR: collision!");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
h->data[hashed_key] = value;
|
||||
}
|
||||
|
||||
void delete(HashTable *h, char *key) {
|
||||
int hashed_key = hash(key);
|
||||
h->data[hashed_key] = NULL;
|
||||
}
|
||||
|
||||
int main() {
|
||||
HashTable *hash_table = new_hashtable();
|
||||
char *key = "hello";
|
||||
insert(hash_table, key, "world");
|
||||
insert(hash_table, "hlleo", "world");
|
||||
char *res = get(hash_table, "hello");
|
||||
|
||||
printf("the value at key '%s' is '%s'", key, res);
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue