From bbf5f2d9d826f7eb69897f74b0724c3a83aafc1f Mon Sep 17 00:00:00 2001 From: "dario.genga" <dario.genga@etu.hesge.ch> Date: Tue, 3 May 2022 13:30:24 +0200 Subject: [PATCH] Add finished ex3 --- ex3/ex3.c | 133 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) diff --git a/ex3/ex3.c b/ex3/ex3.c index 9b4a639..b275775 100644 --- a/ex3/ex3.c +++ b/ex3/ex3.c @@ -8,6 +8,139 @@ #include <string.h> #include <stdbool.h> +#define DEFAULT_CHAR_VALUE '0' + +typedef struct _node { + int value; + struct _node* left; + struct _node* right; +} node; + +typedef struct _linked_list { + char val; + struct _linked_list* next; +} list; + +list* li_create() { + list* li = malloc(sizeof(li)); + li->val = DEFAULT_CHAR_VALUE; + li->next = NULL; + return li; +} + +list* li_create_with_value(char value) { + list* li = li_create(); + li->val = value; + return li; +} + +void li_destroy(list* li) { + list* current = li; + while (current != NULL) { + list *tmp = current; + current = current->next; + free(tmp); + } +} + +void li_add(list* li, char value) { + if (li->val == DEFAULT_CHAR_VALUE) { + li->val = value; + return; + } + list *current = li; + while (current->next != NULL) { + current = current->next; + } + list *new = li_create_with_value(value); + current->next = new; +} + +void li_print(list* li) { + if (li != NULL) { + li_print(li->next); + printf("%c, ", li->val); + } +} + +node* node_create() { + node* nd = malloc(sizeof(node)); + nd->value = 0; + nd->left = NULL; + nd->right = NULL; + return nd; +} + +node* node_create_with_value(int value) { + node* nd = node_create(); + nd->value = value; + return nd; +} + +bool node_is_empty(node* nd) { + return (nd == NULL); +} + +void node_destroy(node *nd) { + if (!node_is_empty(nd)) { + node_destroy(nd->left); + node_destroy(nd->right); + free(nd); + } +} + +void node_add(node* nd, int value) { + if (!node_is_empty(nd)) { + if (value < nd->value) { + if (node_is_empty(nd->left)) { + node* new = node_create_with_value(value); + nd->left = new; + } else { + node_add(nd->left, value); + } + } else { + if (node_is_empty(nd->right)) { + node* new = node_create_with_value(value); + nd->right = new; + } else { + node_add(nd->right, value); + } + } + } +} + +void search_path(node* nd, int value, list* l) { + if (node_is_empty(nd)) { + return NULL; + } + if (nd->value == value) { + li_print(l); + } + + if (value < nd->value) { + li_add(l, 'g'); + search_path(nd->left, value, l); + } else if (value > nd->value) { + li_add(l, 'd'); + search_path(nd->right, value, l); + } +} + int main() { + list* li = li_create(); + node* tree = node_create_with_value(10); + node_add(tree, 0); + node_add(tree, 20); + node_add(tree, -5); + node_add(tree, 5); + node_add(tree, 15); + node_add(tree, 25); + node_add(tree, 22); + node_add(tree, 24); + + search_path(tree, 24, li); + printf("\n"); + + node_destroy(tree); return EXIT_SUCCESS; } -- GitLab