From 7cc6d24b03c4f190a0eab333b5c52112ee8c9af5 Mon Sep 17 00:00:00 2001 From: asankov Date: Fri, 8 May 2020 21:54:23 +0300 Subject: [PATCH] Chapter 3: Add implementation for Exercise 3-2 --- .../strings.c | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 chapter-3/3.3-building-the-data-structure-in-c/strings.c diff --git a/chapter-3/3.3-building-the-data-structure-in-c/strings.c b/chapter-3/3.3-building-the-data-structure-in-c/strings.c new file mode 100644 index 0000000..15d21f4 --- /dev/null +++ b/chapter-3/3.3-building-the-data-structure-in-c/strings.c @@ -0,0 +1,47 @@ +#include +#include +#include + +enum +{ + STRINGS_SIZE = 1000, + _MULTIPLIER = 37, +}; + +typedef struct String String; +struct String +{ + char *val; + String *next; +}; +String *words[STRINGS_SIZE]; + +int hash_string(char *val) +{ + int h = 0; + for (unsigned char *p = (unsigned char *)val; *p != '\0'; p++) + h = _MULTIPLIER * h + *p; + + return h % STRINGS_SIZE; +} + +String *lookup_string(char *val, int create) +{ + int h = hash_string(val); + for (String *s = words[h]; s != NULL; s = s->next) + if (strcmp(s->val, val) == 0) + return s; + + if (create) + { + String *s = (String *)malloc(sizeof(String)); + if (s == NULL) + return NULL; + s->val = val; + s->next = words[h]; + words[h] = s; + return s; + } + + return NULL; +} \ No newline at end of file