Last active
May 10, 2024 09:34
-
-
Save paulfrische/5158b67d46faa4630b39f49865f15c17 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <stdint.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <strings.h> | |
| typedef struct Pair { | |
| struct Pair *next; | |
| const char *key; | |
| void *value; | |
| } Pair; | |
| typedef struct { | |
| Pair **pairs; | |
| size_t capacity; | |
| } HashMap; | |
| HashMap *newHashMap(size_t cap) { | |
| HashMap *map = malloc(sizeof(*map)); | |
| map->capacity = cap; | |
| map->pairs = calloc(cap, sizeof(Pair *)); | |
| return map; | |
| } | |
| void destroyHashMap(HashMap *map) { | |
| for (size_t i = 0; i < map->capacity; i++) { | |
| if (map->pairs[i] == NULL) | |
| continue; | |
| free(map->pairs[i]); | |
| } | |
| free(map->pairs); | |
| free(map); | |
| } | |
| size_t hashString(const char *s) { | |
| size_t hash = 1; | |
| for (size_t i = 0; i < strlen(s); i++) { | |
| size_t old = hash; | |
| hash *= s[i]; | |
| hash ^= old; | |
| } | |
| return hash; | |
| } | |
| void insertHashMap(HashMap *map, const char *key, void *value) { | |
| size_t index = hashString(key) % map->capacity; | |
| Pair *pair = malloc(sizeof(*pair)); | |
| *pair = (Pair){.next = NULL, .key = key, .value = value}; | |
| if (map->pairs[index] == NULL) { | |
| map->pairs[index] = pair; | |
| return; | |
| } | |
| pair->next = map->pairs[index]; | |
| map->pairs[index] = pair; | |
| } | |
| void *getHashMap(HashMap *map, const char *key) { | |
| size_t index = hashString(key) % map->capacity; | |
| if (map->pairs[index] == NULL) { | |
| return NULL; | |
| } | |
| Pair *p = map->pairs[index]; | |
| while (strcmp(p->key, key)) { | |
| p = p->next; | |
| if (p == NULL) { | |
| return NULL; | |
| } | |
| } | |
| return p->value; | |
| } | |
| int main(int argc, char *argv[]) { | |
| HashMap *map = newHashMap(1024); | |
| insertHashMap(map, "asdf", "ASDF"); | |
| insertHashMap(map, "leet", "1337"); | |
| printf("asdf : %s\n", (char *)getHashMap(map, "asdf")); | |
| printf("leet : %s\n", (char *)getHashMap(map, "leet")); | |
| destroyHashMap(map); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment