From f151b796a66adfb1d6b7bf151f2d85fd78cc0a64 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sat, 7 Nov 2026 07:42:12 +0300 Subject: publish --- src/dictionary.c | 234 +++++++++++++++++++++++++++ src/dynamic-array.h | 56 +++++++ src/hash-table.c | 150 +++++++++++++++++ src/hash-table.h | 18 +++ src/red-black-tree.c | 443 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/red-black-tree.h | 17 ++ src/utils.h | 21 +++ 7 files changed, 939 insertions(+) create mode 100644 src/dictionary.c create mode 100644 src/dynamic-array.h create mode 100644 src/hash-table.c create mode 100644 src/hash-table.h create mode 100644 src/red-black-tree.c create mode 100644 src/red-black-tree.h create mode 100644 src/utils.h (limited to 'src') diff --git a/src/dictionary.c b/src/dictionary.c new file mode 100644 index 0000000..291c200 --- /dev/null +++ b/src/dictionary.c @@ -0,0 +1,234 @@ +#include +#include +#include +#include +#include +#include +#include +#include "utils.h" +#include "hash-table.h" +#include "red-black-tree.h" + +#define MENU_ENTRIES_GENERAL(X, ...) \ + X(__VA_ARGS__, EXIT, "EXIT") + +#define MENU_ENTRIES_HASH_TABLE(X, ...) \ + X(__VA_ARGS__, PRINT, "PRINT" ) \ + X(__VA_ARGS__, INSERT, "INSERT" ) \ + X(__VA_ARGS__, DELETE, "DELETE" ) \ + X(__VA_ARGS__, SEARCH, "SEARCH" ) \ + X(__VA_ARGS__, CLEAR, "CLEAR" ) \ + X(__VA_ARGS__, LOAD_FROM_FILE, "LOAD_FROM_FILE") + +#define MENU_ENTRIES_RED_BLACK_TREE(X, ...) \ + X(__VA_ARGS__, PRINT, "PRINT" ) \ + X(__VA_ARGS__, INSERT, "INSERT" ) \ + X(__VA_ARGS__, DELETE, "DELETE" ) \ + X(__VA_ARGS__, SEARCH, "SEARCH" ) \ + X(__VA_ARGS__, CLEAR, "CLEAR" ) \ + X(__VA_ARGS__, LOAD_FROM_FILE, "LOAD_FROM_FILE") + +#define MENU_ENTRY_ENUM(PREFIX, SYMBOL, ...) PREFIX ## _ ## SYMBOL, + +enum menu_entry { + MENU_ENTRIES_GENERAL (MENU_ENTRY_ENUM, GENERAL ) + MENU_ENTRIES_HASH_TABLE (MENU_ENTRY_ENUM, HASH_TABLE ) + MENU_ENTRIES_RED_BLACK_TREE (MENU_ENTRY_ENUM, RED_BLACK_TREE) + MENU_ENTRY_COUNT +}; + +#define MENU_ENTRY_LABEL(SYMBOL_PREFIX, LABEL_PREFIX, SYMBOL, LABEL, ...) \ + [SYMBOL_PREFIX ## _ ## SYMBOL] = LABEL_PREFIX LABEL, + +const char *menu_entry_labels[MENU_ENTRY_COUNT] = { + MENU_ENTRIES_GENERAL (MENU_ENTRY_LABEL, GENERAL, "GENERAL:.........") + MENU_ENTRIES_HASH_TABLE (MENU_ENTRY_LABEL, HASH_TABLE, "HASH-TABLE:......") + MENU_ENTRIES_RED_BLACK_TREE (MENU_ENTRY_LABEL, RED_BLACK_TREE, "RED-BLACK-TREE:..") +}; + +static inline uint8_t +log10u8 (uint8_t value) +{ + return ((value >= 100u) ? 2 : + (value >= 10u) ? 1 + : 0); +} + +static inline void +input_line (const char *what, char **line, size_t *line_size) +{ + printf ("%s: ", what); + size_t length = getline (line, line_size, stdin); + (*line)[length - 1] = '\0'; +} + +static inline char *input_word () +{ + static char *word = NULL; + static size_t word_size = 0; + + input_line ("WORD", &word, &word_size); + return word; +} + +static inline char *input_filename () +{ + static char *filename = NULL; + static size_t filename_size = 0; + + input_line ("FILENAME", &filename, &filename_size); + return filename; +} + +static void +load_from_file (const char *filename, + void (*inserter) (void *context, const char *key, const char *value), + void *context) +{ + static char *line = NULL; + static size_t line_size = 0; + static size_t line_length = 0; + + FILE *stream = fopen (filename, "r"); + if (!stream) { + puts ("UNABLE TO OPEN FILE FOR READING"); + return; + } + + size_t entry_count = 0; + wchar_t wword[1024]; + char word[2048]; + for (;;) { + wint_t wc; + do wc = fgetwc (stream); + while (wc != WEOF && !wcschr (L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", wc)); + ungetwc (wc, stream); + + if (fwscanf (stream, L"%l[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ]", wword) != 1) + break; + + for (wchar_t *head = wword; *head; ++head) + *head = towlower (*head); + + wcstombs (word, wword, 2048); + inserter (context, strdup (word), strdup ("")); + entry_count += 1; + } fclose (stream); + + printf ("FILE LOADED (%zu ENTRIES)\n", entry_count); +} + +int +main (void) +{ + setlocale (LC_ALL, ""); + + // HASH_TABLE hash_table = hash_table_init (193); + HASH_TABLE hash_table = hash_table_init (13); + RED_BLACK_TREE red_black_tree = red_black_tree_init (); + + load_from_file ("dictionary.txt", (void *) hash_table_insert, hash_table); + load_from_file ("dictionary.txt", (void *) red_black_tree_insert, red_black_tree); + + static char *line = NULL; + static size_t line_size = 0; + for (;;) { + enum menu_entry selection = MENU_ENTRY_COUNT; + do { + printf ("\nSELECT:\n"); + for (enum menu_entry entry = 0; entry < MENU_ENTRY_COUNT; ++entry) { + printf (" [%0*u] %s\n", log10u8 (MENU_ENTRY_COUNT) + 1, entry, + menu_entry_labels[entry]); + } printf ("> "); + getline (&line, &line_size, stdin); + + sscanf (line, "%u", &selection); + } while (selection == MENU_ENTRY_COUNT); + + switch (selection) { + case GENERAL_EXIT: { + puts ("EXITING..."); + hash_table_free (hash_table); + red_black_tree_free (red_black_tree); + return EXIT_SUCCESS; + } break; + + case HASH_TABLE_PRINT: { + hash_table_print (hash_table, "hash-table.dot"); + puts ("hash-table.dot:0:0: HASH TABLE PRINTED"); + } break; + + case HASH_TABLE_INSERT: { + const char *word = input_word (); + hash_table_insert (hash_table, word, strdup ("")); + puts ("ENTRY INSERTED"); + } break; + + case HASH_TABLE_DELETE: { + const char *word = input_word (); + if (hash_table_delete (hash_table, word)) + puts ("ENTRY DELETED"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case HASH_TABLE_SEARCH: { + const char *key = input_word (); + const char *value = hash_table_search (hash_table, key); + if (value) + puts ("ENTRY FOUND"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case HASH_TABLE_CLEAR: { + hash_table_clear (hash_table); + puts ("HASH TABLE CLEARED"); + } break; + + case HASH_TABLE_LOAD_FROM_FILE: { + const char *filename = input_filename (); + load_from_file (filename, (void *) hash_table_insert, hash_table); + } break; + + case RED_BLACK_TREE_PRINT: { + red_black_tree_print (red_black_tree, "red-black-tree.dot"); + puts ("red-black-tree.dot:0:0: RED BLACK TREE PRINTED"); + } break; + + case RED_BLACK_TREE_INSERT: { + const char *word = input_word (); + red_black_tree_insert (red_black_tree, word, strdup ("")); + puts ("ENTRY INSERTED"); + } break; + + case RED_BLACK_TREE_DELETE: { + const char *key = input_word (); + if (red_black_tree_delete (red_black_tree, key)) + puts ("ENTRY DELETED"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case RED_BLACK_TREE_SEARCH: { + const char *key = input_word (); + const char *value = red_black_tree_search (red_black_tree, key); + if (value) + puts ("ENTRY FOUND"); + else + puts ("ENTRY NOT FOUND"); + } break; + + case RED_BLACK_TREE_CLEAR: { + red_black_tree_clear (red_black_tree); + puts ("RED BLACK TREE CLEARED"); + } break; + + case RED_BLACK_TREE_LOAD_FROM_FILE: { + const char *filename = input_filename (); + load_from_file (filename, (void *) red_black_tree_insert, red_black_tree); + } break; + default: break; + } + } +} diff --git a/src/dynamic-array.h b/src/dynamic-array.h new file mode 100644 index 0000000..212e9f4 --- /dev/null +++ b/src/dynamic-array.h @@ -0,0 +1,56 @@ +#ifndef INCLUDED_DYNAMIC_ARRAY_H +#define INCLUDED_DYNAMIC_ARRAY_H + +#include "utils.h" + +#ifndef DYNAMIC_ARRAY_INIT_CAP +#define DYNAMIC_ARRAY_INIT_CAP 256 +#endif + +#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \ + ({ \ + if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \ + if ((DYNAMIC_ARRAY).capacity == 0) \ + (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \ + while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \ + (DYNAMIC_ARRAY).capacity *= 2; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + } \ + }) + +#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \ + ({ \ + (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + \ + }) + +#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ + }) + +#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \ + memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \ + (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \ + (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \ + }) + +#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; }) + +#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items) + +#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \ + typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \ + ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM) + +#endif diff --git a/src/hash-table.c b/src/hash-table.c new file mode 100644 index 0000000..7b6c983 --- /dev/null +++ b/src/hash-table.c @@ -0,0 +1,150 @@ +#include "hash-table.h" +#include +#include + +typedef struct entry *ENTRY; +struct entry { + ENTRY next; + char *key; + char *value; +}; + +struct hash_table { + size_t bucket_count; + ENTRY buckets[]; +}; + +// NOTE(cmmm): hash * 33 ^ c might be better +static inline size_t +hash_function_djb2 (const char *str) +{ + size_t hash = 5381; + unsigned char c; + + while ((c = *str++)) + hash = ((hash << 5) + hash) + c; // hash * 33 + c + + return hash; +} + +void +hash_table_print (HASH_TABLE hash_table, const char *filename) +{ + FILE *stream = fopen (filename, "w"); + fprintf (stream, "digraph hash_table {\n"); + fprintf (stream, "\trankdir = LR\n"); + fprintf (stream, "\tnode [shape = record]\n\n"); + size_t entry_idx = 0; + size_t bucket_idx = 0; + for (ENTRY *bucket = hash_table->buckets; + bucket < hash_table->buckets + hash_table->bucket_count; ++bucket) + { + fprintf (stream, "\tbucket%zu [label = \"%zu\"]\n", bucket_idx, bucket_idx); + + size_t saved_idx = entry_idx; + for (ENTRY entry = *bucket; entry; entry = entry->next) + fprintf (stream, "\tentry%zu [label = \"%s\"]\n", entry_idx++, entry->key); + + entry_idx = saved_idx; + for (ENTRY entry = *bucket; entry; entry = entry->next) { + if (entry == *bucket) + fprintf (stream, "\tbucket%zu -> ", bucket_idx); + fprintf (stream, "entry%zu", entry_idx++); + if (entry->next) + fprintf (stream, " -> "); + } fprintf (stream, "\n\n"); + + bucket_idx += 1; + } fprintf (stream, "}\n"); + fclose (stream); +} + +HASH_TABLE +hash_table_init (size_t bucket_count) +{ + HASH_TABLE hash_table = malloc (sizeof (*hash_table) + + bucket_count*sizeof (*hash_table->buckets)); + + hash_table->bucket_count = bucket_count; + memset (hash_table->buckets, 0, + hash_table->bucket_count*sizeof (*hash_table->buckets)); + + return hash_table; +} + +void +hash_table_clear (HASH_TABLE hash_table) +{ + if (!hash_table) + return; + + for (ENTRY *bucket = hash_table->buckets; + bucket < hash_table->buckets + hash_table->bucket_count; ++bucket) { + for (ENTRY entry = *bucket, next; entry; entry = next) { + next = entry->next; + free (entry->key); + free (entry->value); + free (entry); + } *bucket = NULL; + } +} + +void +hash_table_free (HASH_TABLE hash_table) +{ + hash_table_clear (hash_table); + free (hash_table); +} + +void +hash_table_insert (HASH_TABLE hash_table, const char *key, const char *value) +{ + size_t hash = hash_function_djb2 (key) % hash_table->bucket_count; + + ENTRY *entry = &hash_table->buckets[hash]; + while (*entry) { + if (!strcmp (key, (*entry)->key)) { // found + free ((*entry)->value); + (*entry)->value = strdup (value); + return; + } else entry = &(*entry)->next; + } + + // not found + *entry = malloc (sizeof (**entry)); + (*entry)->next = NULL; + (*entry)->key = strdup (key); + (*entry)->value = strdup (value); +} + +bool +hash_table_delete (HASH_TABLE hash_table, const char *key) +{ + size_t hash = hash_function_djb2 (key) % hash_table->bucket_count; + ENTRY *entry = &hash_table->buckets[hash]; + while (*entry) { + if (!strcmp (key, (*entry)->key)) { // found + ENTRY next = (*entry)->next; + + free ((*entry)->key); + free ((*entry)->value); + free (*entry); + + *entry = next; + + return true; + } else entry = &(*entry)->next; + } return false; +} + +const char * +hash_table_search (HASH_TABLE hash_table, const char *key) +{ + size_t hash = hash_function_djb2 (key) % hash_table->bucket_count; + ENTRY entry = hash_table->buckets[hash]; + while (entry) { + if (!strcmp (key, entry->key)) + return entry->value; + else entry = entry->next; + } return NULL; +} diff --git a/src/hash-table.h b/src/hash-table.h new file mode 100644 index 0000000..b8f14bc --- /dev/null +++ b/src/hash-table.h @@ -0,0 +1,18 @@ +#ifndef INCLUDED_HASH_TABLE_H +#define INCLUDED_HASH_TABLE_H + +#include +#include + +typedef struct hash_table *HASH_TABLE; + +HASH_TABLE hash_table_init (size_t bucket_count); +void hash_table_print (HASH_TABLE, const char *filename); +void hash_table_clear (HASH_TABLE); +void hash_table_free (HASH_TABLE); + +void hash_table_insert (HASH_TABLE, const char *key, const char *value); +bool hash_table_delete (HASH_TABLE, const char *key); +const char *hash_table_search (HASH_TABLE, const char *key); + +#endif diff --git a/src/red-black-tree.c b/src/red-black-tree.c new file mode 100644 index 0000000..62be0d8 --- /dev/null +++ b/src/red-black-tree.c @@ -0,0 +1,443 @@ +#include "red-black-tree.h" +#include "dynamic-array.h" +#include +#include +#include +#include + +enum color { + COLOR_RED, + COLOR_BLACK, +}; + +typedef struct node *NODE; +struct node { + enum color color; + NODE parent; + NODE left; + NODE right; + char *key; + char *value; +}; + +struct red_black_tree { + NODE root; +}; + +struct nodes { + NODE *items; + uint32_t count; + uint32_t capacity; +}; + +void +red_black_tree_print (RED_BLACK_TREE red_black_tree, const char *filename) +{ + FILE *file = fopen (filename, "w"); + fprintf (file, "digraph red_black_tree {\n"); + fprintf (file, "\tnode [style = filled, fillcolor = black, fontcolor = white]\n"); + + struct nodes stack1 = {0}; + struct nodes stack2 = {0}; + struct nodes *front_stack = &stack1; + struct nodes *back_stack = &stack2; + if (red_black_tree->root) + DYNAMIC_ARRAY_APPEND (*front_stack, red_black_tree->root); + size_t null_count = 0; + while (front_stack->count) { + DYNAMIC_ARRAY_RESET (*back_stack); + DYNAMIC_ARRAY_FOREACH(node, *front_stack) { + fprintf (file, "\t\"%s\" [fillcolor = %s]\n", (*node)->key, (*node)->color ? "black" : "webmaroon"); + + if ((*node)->left) { + DYNAMIC_ARRAY_APPEND (*back_stack, (*node)->left); + fprintf (file, "\t\"%s\" -> \"%s\"\n", (*node)->key, (*node)->left->key); + } else { + fprintf (file, "\tnull%zu [shape = circle, label = \"\", width = 0.2]\n", null_count); + fprintf (file, "\t\"%s\" -> null%zu\n", (*node)->key, null_count); + null_count += 1; + } + + if ((*node)->right) { + DYNAMIC_ARRAY_APPEND (*back_stack, (*node)->right); + fprintf (file, "\t\"%s\" -> \"%s\"\n", (*node)->key, (*node)->right->key); + } else { + fprintf (file, "\tnull%zu [shape = circle, label = \"\", width = 0.2]\n", null_count); + fprintf (file, "\t\"%s\" -> null%zu\n", (*node)->key, null_count); + null_count += 1; + } + } SWAP (front_stack, back_stack); + } fprintf (file, "}\n"); + fclose (file); +} + +RED_BLACK_TREE +red_black_tree_init (void) +{ + return calloc (1, sizeof (struct red_black_tree)); +} + +void +red_black_tree_clear (RED_BLACK_TREE red_black_tree) +{ + if (!red_black_tree || !red_black_tree->root) + return; + + struct nodes stack = {0}; + DYNAMIC_ARRAY_APPEND (stack, red_black_tree->root); + while (stack.count) { + NODE node = stack.items[stack.count - 1]; + stack.count -= 1; + + if (node->left) + DYNAMIC_ARRAY_APPEND (stack, node->left); + + if (node->right) + DYNAMIC_ARRAY_APPEND (stack, node->right); + + free (node->key ); + free (node->value); + free (node ); + } red_black_tree->root = NULL; +} + +void +red_black_tree_free (RED_BLACK_TREE red_black_tree) +{ + red_black_tree_clear (red_black_tree); + free (red_black_tree); +} + +static inline void +rotate_left (RED_BLACK_TREE red_black_tree, NODE node) +{ + NODE y = node->right; + if (!y) return; + node->right = y->left; + if (y->left) + y->left->parent = node; + + y->parent = node->parent; + if (!node->parent) { + red_black_tree->root = y; + } else if (node == node->parent->left) { + node->parent->left = y; + } else { + node->parent->right = y; + } + + y->left = node; + node->parent = y; +} + +static inline void +rotate_right (RED_BLACK_TREE red_black_tree, NODE node) +{ + NODE y = node->left; + node->left = y->right; + if (y->right) { + y->right->parent = node; + } + y->parent = node->parent; + if (!node->parent) { + red_black_tree->root = y; + } else if (node == node->parent->right) { + node->parent->right = y; + } else { + node->parent->left = y; + } + y->right = node; + node->parent = y; +} + +void +red_black_tree_insert (RED_BLACK_TREE red_black_tree, + const char *key, const char *value) +{ + // change value if already exists + for (NODE head = red_black_tree->root, next; head; head = next) { + int difference = strcmp (head->key, key); + if (!difference) { + free (head->value); + head->value = strdup (value); + return; + } + next = difference > 0 ? head->left : head->right; + } + + NODE node = calloc (1, sizeof (*node)); + node->key = strdup (key); + node->value = strdup (value); + + // find parent + for (NODE head = red_black_tree->root, next; head; head = next) { + node->parent = head; + next = strcmp (node->key, head->key) < 0 ? head->left + : head->right; + } + + // no parent + if (!node->parent) { + node->color = COLOR_BLACK; + red_black_tree->root = node; + return; + } + + // attach + if (strcmp (node->key, node->parent->key) < 0) { + node->parent->left = node; + } else { + node->parent->right = node; + } + + // no grandparent + if (!node->parent->parent) { + return; + } + + // fix insert + NODE u; + while (node->parent->color == COLOR_RED) { + if (node->parent == node->parent->parent->right) { + u = node->parent->parent->left; // uncle + if (u && u->color == COLOR_RED) { // case 3.1 + u->color = COLOR_BLACK; + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + node = node->parent->parent; + } else { + if (node == node->parent->left) { // case 3.2.2 + node = node->parent; + rotate_right (red_black_tree, node); + } + + // case 3.2.1 + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + rotate_left (red_black_tree, node->parent->parent); + } + } else { + u = node->parent->parent->right; // uncle + + if (u && u->color == COLOR_RED) { // mirror case 3.1 + u->color = COLOR_BLACK; + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + node = node->parent->parent; + } else { + if (node == node->parent->right) { // mirror case 3.2.2 + node = node->parent; + rotate_left (red_black_tree, node); + } + + // mirror case 3.2.1 + node->parent->color = COLOR_BLACK; + node->parent->parent->color = COLOR_RED; + rotate_right (red_black_tree, node->parent->parent); + } + } + if (node == red_black_tree->root) { + break; + } + } + red_black_tree->root->color = COLOR_BLACK; +} + + +static inline NODE +minimum (NODE node) +{ + if (!node) + return NULL; // patch + + while (node->left) + node = node->left; + + return node; +} + +// https://github.com/xieqing/red-black-tree +bool +red_black_tree_delete (RED_BLACK_TREE red_black_tree, const char *key) +{ + NODE node = NULL; + NODE target = NULL; + NODE child = NULL; + + for (NODE head = red_black_tree->root, next; head; head = next) { + if (!strcmp (head->key, key)) { + node = head; + break; + } + next = strcmp (head->key, key) <= 0 ? head->right : head->left; + } + + if (!node) + return false; + + /* choose node's in-order successor if it has two children */ + if (!node->left || !node->right) { + target = node; + } else { + target = node->right ? minimum (node->right) : node; /* node->right must not be NIL, thus move down */ + + /* data swapped */ + SWAP (node->key, target->key); + SWAP (node->value, target->value); + } + + child = !target->left ? target->right : target->left; /* child may be NIL */ + + /* + * deletion from red-black tree + * 4-children cluster (RED target node) becomes 3-children cluster + * done + * 3-children cluster (RED target node) becomes 2-children cluster + * done + * 3-children cluster (BLACK target node, RED child node) becomes 2-children cluster + * paint child node BLACK, and done + * + * 2-children root cluster (BLACK target node, BLACK child node) becomes 0-children root cluster + * done + * + * 2-children cluster (BLACK target node, 4-children sibling cluster) becomes 3-children cluster + * transfer, and done + * 2-children cluster (BLACK target node, 3-children sibling cluster) becomes 2-children cluster + * transfer, and done + * + * 2-children cluster (BLACK target node, 2-children sibling cluster, 3/4-children parent cluster) becomes 3-children cluster + * fuse, paint parent node BLACK, and done + * 2-children cluster (BLACK target node, 2-children sibling cluster, 2-children parent cluster) becomes 3-children cluster + * fuse, and delete parent node from parent cluster + */ + if (target->color == COLOR_BLACK) { + if (child && child->color == COLOR_RED) { + /* deletion from 3-children cluster (BLACK target node, RED child node) */ + child->color = COLOR_BLACK; + } else if (target == red_black_tree->root) { + /* deletion from 2-children root cluster (BLACK target node, BLACK child node) */ + } else { + /* deletion from 2-children cluster (BLACK target node, ...) */ + // REPAIR + NODE current = target; + NODE sibling; + do { + if (current == current->parent->left) { + sibling = current->parent->right; + + if (sibling && sibling->color == COLOR_RED) { + /* perform an adjustment (3-children parent cluster has two representations) */ + sibling->color = COLOR_BLACK; + current->parent->color = COLOR_RED; + rotate_left (red_black_tree, current->parent); + sibling = current->parent->right; + } + + /* sibling node must be BLACK now */ + if ((!sibling->right || sibling->right->color == COLOR_BLACK) && + (!sibling->left || sibling->left ->color == COLOR_BLACK)) { + /* 2-children sibling cluster, fuse by recoloring */ + sibling->color = COLOR_RED; + if (current->parent->color == COLOR_RED) { /* 3/4-children parent cluster */ + current->parent->color = COLOR_BLACK; + break; /* goto break */ + } else { /* 2-children parent cluster */ + current = current->parent; /* goto loop */ + } + } else { + /* 3/4-children sibling cluster */ + + /* perform an adjustment (3-children sibling cluster has two representations) */ + if (!sibling->right || sibling->right->color == COLOR_BLACK) { + sibling->left->color = COLOR_BLACK; + sibling->color = COLOR_RED; + rotate_right (red_black_tree, sibling); + sibling = current->parent->right; + } + + /* transfer by rotation and recoloring */ + sibling->color = current->parent->color; + current->parent->color = COLOR_BLACK; + sibling->right->color = COLOR_BLACK; + rotate_left (red_black_tree, current->parent); + break; /* goto break */ + } + } else { + sibling = current->parent->left; + + if (sibling->color == COLOR_RED) { + /* perform an adjustment (3-children parent cluster has two representations) */ + sibling->color = COLOR_BLACK; + current->parent->color = COLOR_RED; + rotate_right (red_black_tree, current->parent); + sibling = current->parent->left; + } + + /* sibling node must be BLACK now */ + + if ((!sibling->right || sibling->right->color == COLOR_BLACK) && + (!sibling->left || sibling->left ->color == COLOR_BLACK)) { + /* 2-children sibling cluster, fuse by recoloring */ + sibling->color = COLOR_RED; + if (current->parent->color == COLOR_RED) { /* 3/4-children parent cluster */ + current->parent->color = COLOR_BLACK; + break; /* goto break */ + } else { /* 2-children parent cluster */ + current = current->parent; /* goto loop */ + } + } else { + /* 3/4-children sibling cluster */ + + /* perform an adjustment (3-children sibling cluster has two representations) */ + if (!sibling->left || sibling->left->color == COLOR_BLACK) { + sibling->right->color = COLOR_BLACK; + sibling->color = COLOR_RED; + rotate_left (red_black_tree, sibling); + sibling = current->parent->left; + } + + /* transfer by rotation and recoloring */ + sibling->color = current->parent->color; + current->parent->color = COLOR_BLACK; + sibling->left->color = COLOR_BLACK; + rotate_right (red_black_tree, current->parent); + break; /* goto break */ + } + } + } while (current != red_black_tree->root); + } + } else { + /* deletion from 4-children cluster (RED target node) */ + /* deletion from 3-children cluster (RED target node) */ + } + + if (child) + child->parent = target->parent; + + if (target->parent) { + if (target == target->parent->left) + target->parent->left = child; + else if (target == target->parent->right) + target->parent->right = child; + } else { + red_black_tree->root = child; + } + + free (target->key); + free (target->value); + free (target); + + return true; +} + +const char * +red_black_tree_search (RED_BLACK_TREE red_black_tree, const char *key) +{ + for (NODE head = red_black_tree->root, next; head; head = next) { + int difference = strcmp (head->key, key); + if (!difference) return head->value; + next = difference > 0 ? head->left : head->right; + } + + return NULL; +} diff --git a/src/red-black-tree.h b/src/red-black-tree.h new file mode 100644 index 0000000..a18984e --- /dev/null +++ b/src/red-black-tree.h @@ -0,0 +1,17 @@ +#ifndef INCLUDED_RED_BLACK_TREE_H +#define INCLUDED_RED_BLACK_TREE_H + +#include + +typedef struct red_black_tree *RED_BLACK_TREE; + +RED_BLACK_TREE red_black_tree_init (void); +void red_black_tree_print (RED_BLACK_TREE, const char *filename); +void red_black_tree_clear (RED_BLACK_TREE); +void red_black_tree_free (RED_BLACK_TREE); + +void red_black_tree_insert (RED_BLACK_TREE, const char *key, const char *value); +bool red_black_tree_delete (RED_BLACK_TREE, const char *key); +const char *red_black_tree_search (RED_BLACK_TREE, const char *key); + +#endif diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..d4d451f --- /dev/null +++ b/src/utils.h @@ -0,0 +1,21 @@ +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include + +#define MALLOC malloc +#define REALLOC realloc +#define FREE free +#define ASSERT assert + +#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP) + +#define SWAP(A, B) \ + ({ \ + typeof (A) tmp = (A); \ + (A) = (B); \ + (B) = tmp; \ + }) + +#endif -- cgit v1.3.1