diff --git a/du6/program.c b/du6/program.c index 2de5e8f..661d43d 100644 --- a/du6/program.c +++ b/du6/program.c @@ -2,93 +2,102 @@ #include #include -#define VELKOST 256 +#define SIZE 256 -struct Uzol{ - char text[VELKOST]; - struct Uzol* ano; - struct Uzol* nie; +struct tree { + char text[SIZE]; + struct tree* yes; + struct tree* no; }; -struct Uzol* nacitaj_uzol(){ - char riadok[VELKOST]; +int count_items = 0; - if(!fgets(riadok, VELKOST, stdin)) +struct tree* read_tree() { + char buffer[SIZE]; + + if (!fgets(buffer, SIZE, stdin)) return NULL; - if(riadok[0] == '\n') + if (buffer[0] == '\n') return NULL; - struct Uzol* u = malloc(sizeof(struct Uzol)); - strcpy(u->text, riadok); - u->ano = NULL; - u->nie = NULL; + struct tree* node = malloc(sizeof(struct tree)); + strcpy(node->text, buffer); + node->yes = NULL; + node->no = NULL; - if(riadok[0] == '*'){ - return u; + if (buffer[0] == '*') { + count_items++; + return node; } - u->ano = nacitaj_uzol(); - u->nie = nacitaj_uzol(); - return u; + node->yes = read_tree(); + if (!node->yes) { + printf("Chyba\n"); + exit(0); + } + + node->no = read_tree(); + if (!node->no) { + printf("Chyba\n"); + exit(0); + } + + return node; } -void zrus_strom(struct Uzol* u){ - if(!u) return; - zrus_strom(u->ano); - zrus_strom(u->nie); - free(u); +void destroy_tree(struct tree* t) { + if (!t) return; + destroy_tree(t->yes); + destroy_tree(t->no); + free(t); } -int pocet_tovarov(struct Uzol* u){ - if(!u) return 0; - if(u->text[0] == '*') return 1; - return pocet_tovarov(u->ano) + pocet_tovarov(u->nie); -} +void run(struct tree* t) { + printf("%s", t->text); -void spusti_system(struct Uzol* u){ - if(u->text[0] == '*'){ - printf("%s", u->text); + if (t->text[0] == '*') { printf("Koniec\n"); return; } - printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n"); - printf("%s", u->text); + printf("Odpovedajte 'a' alebo 'n'\n"); char c; - if(scanf(" %c", &c) != 1){ - printf("Koniec vstupu\n"); + if (scanf(" %c", &c) != 1) { + printf("Chyba\n"); return; } - if(c == 'a'){ - spusti_system(u->ano); - } - else if(c == 'n'){ - spusti_system(u->nie); - } - else{ - printf("Nerozumiem\n"); - } + if (c == 'a') + run(t->yes); + else if (c == 'n') + run(t->no); + else + printf("Chyba\n"); } -int main(){ - struct Uzol* koren = nacitaj_uzol(); +int main() { + struct tree* root = read_tree(); - if(!koren){ - printf("Chyba: nepodarilo sa nacitat bazu pravidiel.\n"); + if (!root) { + printf("Chyba\n"); return 0; } - int pocet = pocet_tovarov(koren); + char line[SIZE]; + if (!fgets(line, SIZE, stdin) || line[0] != '\n') { + printf("Chyba\n"); + destroy_tree(root); + return 0; + } - printf("Expert z bufetu to vie.\n"); - printf("Pozna %d druhov ovocia a zeleniny.\n", pocet); + printf("MUDrC to vie.\n"); + printf("Pozna %d druhov ovocia a zeleniny.\n", count_items); - spusti_system(koren); - zrus_strom(koren); + run(root); + destroy_tree(root); return 0; }