From 6ec70db7995b9b897dd1fc0a3f62eb465a8de69d Mon Sep 17 00:00:00 2001 From: Kozar Date: Tue, 12 Nov 2024 16:09:51 +0000 Subject: [PATCH] Initializacia --- cv7/program.c | 60 ++++++++++++++++++++++----------------------------- 1 file changed, 26 insertions(+), 34 deletions(-) diff --git a/cv7/program.c b/cv7/program.c index 53b94ec..0c69c32 100644 --- a/cv7/program.c +++ b/cv7/program.c @@ -1,6 +1,5 @@ #include #include -#include #include #define SIZE 100 @@ -13,52 +12,41 @@ struct tree { struct tree* read_tree() { char buffer[SIZE]; - - while (fgets(buffer, SIZE, stdin)) { - buffer[strcspn(buffer, "\n")] = 0; - - if (buffer[0] == '\0') { - continue; - } - - struct tree* node = calloc(1, sizeof(struct tree)); - strncpy(node->value, buffer, SIZE - 1); - return node; + memset(buffer, 0, SIZE); + + if (!fgets(buffer, SIZE, stdin) || buffer[0] == '\n') { + return NULL; } - - return NULL; + + buffer[strcspn(buffer, "\n")] = 0; + + struct tree* node = (struct tree*)calloc(1, sizeof(struct tree)); + strncpy(node->value, buffer, SIZE - 1); + + return node; } - - struct tree* load_tree() { struct tree* node = read_tree(); if (!node) { return NULL; } - if (node->value[0] != '*') { + if (node->value[0] != '*') { node->left = load_tree(); node->right = load_tree(); - } else { - node->left = NULL; - node->right = NULL; } - + return node; } - - - - void run_tree(struct tree* tree) { if (!tree) { return; } if (tree->value[0] == '*') { - printf("*%s\nKoniec\n", tree->value + 1); + printf("%s\nKoniec\n", tree->value + 1); return; } @@ -81,16 +69,20 @@ void run_tree(struct tree* tree) { } void destroy_tree(struct tree* tree) { - if (tree->left != NULL) { - destroy_tree(tree->left); - } - if (tree->right != NULL) { - destroy_tree(tree->right); + if (!tree) { + return; } + + destroy_tree(tree->left); + destroy_tree(tree->right); free(tree); } void count_items(struct tree* tree, int* count) { + if (!tree) { + return; + } + if (tree->left == NULL && tree->right == NULL) { (*count)++; } else { @@ -101,9 +93,10 @@ void count_items(struct tree* tree, int* count) { int main() { struct tree* root = load_tree(); + printf("Expert z bufetu to vie.\n"); - if (!root) { + if (!root) { printf("Chybna databaza\n"); return 0; } @@ -114,8 +107,7 @@ int main() { printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n"); run_tree(root); + destroy_tree(root); return 0; } - -