pvjc26/du5/program.c
2026-04-08 16:17:49 +02:00

104 lines
2.3 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 1024
struct strom {
char hodnota[SIZE];
struct strom* ano;
struct strom* nie;
};
struct strom* nacitaj_strom() {
char buffer[SIZE];
memset(buffer, 0, SIZE);
char* r = fgets(buffer, SIZE, stdin);
if (r == NULL) return NULL;
if (buffer[0] == '\n' || buffer[0] == '\0') return NULL;
struct strom* uzol = calloc(1, sizeof(struct strom));
memcpy(uzol->hodnota, buffer, SIZE);
if (buffer[0] != '*') {
uzol->ano = nacitaj_strom();
uzol->nie = nacitaj_strom();
}
return uzol;
}
void znic_strom(struct strom* uzol) {
if (uzol == NULL) return;
znic_strom(uzol->ano);
znic_strom(uzol->nie);
free(uzol);
}
int spocitaj_listy(struct strom* uzol) {
if (uzol == NULL) return 0;
if (uzol->ano == NULL && uzol->nie == NULL) return 1;
return spocitaj_listy(uzol->ano) + spocitaj_listy(uzol->nie);
}
void spusti_system(struct strom* uzol) {
if (uzol == NULL) return;
printf("%s", uzol->hodnota);
if (uzol->ano == NULL && uzol->nie == NULL) {
printf("Koniec\n");
return;
}
char odpoved[SIZE];
memset(odpoved, 0, SIZE);
if (fgets(odpoved, SIZE, stdin) == NULL) {
printf("Chybny vstup.\n");
return;
}
if (odpoved[0] == 'a') {
spusti_system(uzol->ano);
} else if (odpoved[0] == 'n') {
spusti_system(uzol->nie);
} else {
printf("Chybny vstup.\n");
}
}
int main() {
struct strom* koren = nacitaj_strom();
if (koren) {
printf("koren: %s", koren->hodnota);
printf("ano: %s", koren->ano ? koren->ano->hodnota : "NULL\n");
printf("nie: %s", koren->nie ? koren->nie->hodnota : "NULL\n");
}
if (koren == NULL) {
printf("Chyba: nepodarilo sa nacitat bazu pravidiel.\n");
return 1;
}
char sep[SIZE];
if (fgets(sep, SIZE, stdin) == NULL || sep[0] != '\n') {
printf("Chyba: nepodarilo sa nacitat bazu pravidiel.\n");
znic_strom(koren);
return 1;
}
int pocet = spocitaj_listy(koren);
printf("Expert z bufetu to vie.\n");
printf("Pozna %d druhov ovocia a zeleniny.\n", pocet);
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
spusti_system(koren);
znic_strom(koren);
return 0;
}