76 lines
1.8 KiB
C
76 lines
1.8 KiB
C
#include "a_train.h"
|
|
|
|
struct car* add_car(struct car* first, const char* target) {
|
|
// Vytvorenie nového vozňa
|
|
struct car* newcar = calloc(1, sizeof(struct car));
|
|
if (!newcar) return first;
|
|
|
|
strcpy(newcar->value, target);
|
|
|
|
// Ak bol zoznam prázdny — použijeme ternárny operator
|
|
first = (first == NULL) ? newcar : first;
|
|
|
|
// Ak bol prázdny, máme hotovo
|
|
if (first == newcar)
|
|
return first;
|
|
|
|
// Nájdeme koniec zoznamu
|
|
struct car* this = first;
|
|
while (this->next != NULL)
|
|
this = this->next;
|
|
|
|
this->next = newcar;
|
|
return first;
|
|
}
|
|
|
|
void print_train(struct car* first) {
|
|
// ZMENA: jednoduchší zápis cyklu
|
|
for (struct car* c = first; c != NULL; c = c->next) {
|
|
printf("%s\n", c->value);
|
|
}
|
|
}
|
|
|
|
void cancel_train(struct car* first) {
|
|
if (first == NULL) return;
|
|
cancel_train(first->next);
|
|
free(first);
|
|
}
|
|
|
|
struct car* clear_train(struct car* first, const char* name) {
|
|
|
|
// Ak je zoznam prázdny
|
|
if (first == NULL) return NULL;
|
|
|
|
// Odstraňovanie prvkov zo začiatku
|
|
while (first && strcmp(first->value, name) == 0) {
|
|
struct car* tmp = first->next;
|
|
free(first);
|
|
first = tmp;
|
|
}
|
|
|
|
// Ak sa všetko odstránilo
|
|
if (first == NULL) return NULL;
|
|
|
|
struct car* prev = first;
|
|
|
|
// ZMENA: prepis vnútornej logiky bez zmeny výsledku
|
|
while (prev->next) {
|
|
|
|
// Ak sa má prvok vymazať
|
|
if (strcmp(prev->next->value, name) == 0) {
|
|
|
|
struct car* to_delete = prev->next;
|
|
|
|
// Preskočíme uzol a uvoľníme ho
|
|
prev->next = to_delete->next;
|
|
free(to_delete);
|
|
|
|
} else {
|
|
// ZMENA: iný štýl zápisu inkrementácie
|
|
prev = prev->next;
|
|
}
|
|
}
|
|
|
|
return first;
|
|
}
|