Last active
October 27, 2017 11:13
-
-
Save sat0b/388a9307492808cabeaf9596bc922918 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 <stdio.h> | |
| #include <string.h> | |
| #include <stdlib.h> | |
| #define MAX_SIZE 10 | |
| //#define MAX_SIZE 1071 | |
| typedef struct _table { | |
| int value; | |
| char *key; | |
| struct _table *next; | |
| } Table; | |
| int hash(char *key) { | |
| int s = 17; | |
| for (char *p = key; *p != '\0'; p++) { | |
| s += 17 * s; | |
| s += 17 * (*p); | |
| } | |
| return s % MAX_SIZE; | |
| } | |
| Table *init_table(char *key, int value) { | |
| Table *t = malloc(sizeof(Table)); | |
| t->key = malloc(sizeof(char) * 1024); | |
| strncpy(t->key, key, 1024); | |
| t->value = value; | |
| t->next = NULL; | |
| return t; | |
| } | |
| void set_table(Table **table, char *key, int value) { | |
| Table **p = &table[hash(key)]; | |
| while (*p && strcmp((*p)->key, key) != 0) | |
| p = &(*p)->next; | |
| *p = init_table(key, value); | |
| } | |
| void set_table2(Table **table, char *key, int value) { | |
| int hashed_key = hash(key); | |
| Table *t = init_table(key, value); | |
| if (!table[hashed_key] || strcmp(table[hashed_key]->key, key) == 0) { | |
| table[hashed_key] = t; | |
| return; | |
| } | |
| Table *p = table[hashed_key]; | |
| while (p->next) { | |
| if (strcmp(p->next->key, key) == 0) | |
| break; | |
| p = p->next; | |
| } | |
| p->next = t; | |
| } | |
| int get_table(Table **table, char *key) { | |
| for (Table *p = table[hash(key)]; p; p = p->next) { | |
| if (strcmp(p->key, key) == 0) | |
| return p->value; | |
| } | |
| return -1; | |
| } | |
| int main(int argc, char **argv) { | |
| Table *table[1024] = {0}; | |
| set_table(table, "foo", 1); | |
| set_table(table, "bar", 2); | |
| set_table(table, "goo", 3); | |
| set_table(table, "off", 4); | |
| set_table(table, "foo", 5); | |
| printf("%d:%s:%d\n", hash("foo"), "foo", get_table(table, "foo")); | |
| printf("%d:%s:%d\n", hash("bar"), "bar", get_table(table, "bar")); | |
| printf("%d:%s:%d\n", hash("goo"), "goo", get_table(table, "goo")); | |
| printf("%d:%s:%d\n", hash("off"), "off", get_table(table, "off")); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment