From db9350231b3cca7d115c6390117cf32cca7da106 Mon Sep 17 00:00:00 2001 From: Denis Landa Date: Thu, 6 Nov 2025 17:39:58 +0100 Subject: [PATCH] 1 --- du4/a_train.c | 81 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 74 insertions(+), 7 deletions(-) diff --git a/du4/a_train.c b/du4/a_train.c index 9191c43..a29e3da 100644 --- a/du4/a_train.c +++ b/du4/a_train.c @@ -1,18 +1,85 @@ -#include "a_train.h" #include +#include +#include +#include "a_train.h" -struct car* add_car(struct car* first,const char* target) { - return NULL; +/** + * Prida vozen na koniec vlaku. + */ +struct car* add_car(struct car* first, const char* target) { + // vytvorenie noveho vozna + struct car* newcar = calloc(1, sizeof(struct car)); + if (newcar == NULL) { + return first; // ak zlyha alokacia, vrat povodny zoznam + } + + strcpy(newcar->value, target); + newcar->next = NULL; + + // ak je vlak prazdny + if (first == NULL) { + return newcar; + } + + // najdi posledny vozen + struct car* this = first; + while (this->next != NULL) { + this = this->next; + } + + // pripoj novy vozen + this->next = newcar; + return first; } -dddddddd + +/** + * Vypise vsetky vozne vo vlaku. + */ void print_train(struct car* first) { + struct car* this = first; + while (this != NULL) { + printf("%s\n", this->value); + this = this->next; + } } +/** + * Zrusenie vsetkych voznov vo vlaku. + */ void cancel_train(struct car* first) { + if (first == NULL) return; + + // rekurzivne uvolnenie + cancel_train(first->next); + free(first); } - +/** + * Vyradenie vsetkych voznov, ktorych cielova stanica je target. + */ struct car* clear_train(struct car* first, const char* target) { - return NULL; -} + struct car* current = first; + struct car* prev = NULL; + while (current != NULL) { + if (strcmp(current->value, target) == 0) { + // treba zmazat tento vozen + struct car* to_delete = current; + if (prev == NULL) { + // mazeme prvy prvok + first = current->next; + } else { + // mazeme stredny alebo posledny prvok + prev->next = current->next; + } + current = current->next; + free(to_delete); + } else { + // presun dalej + prev = current; + current = current->next; + } + } + + return first; +}