From 6f7842f86dc0692142ed332b75238d8f1ba7b452 Mon Sep 17 00:00:00 2001 From: Bohdan Kapliuk Date: Mon, 21 Oct 2024 17:15:46 +0300 Subject: [PATCH] cv4 --- cv4/a_train.c | 47 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 12 deletions(-) diff --git a/cv4/a_train.c b/cv4/a_train.c index 6a76c4e..88deebe 100644 --- a/cv4/a_train.c +++ b/cv4/a_train.c @@ -6,6 +6,9 @@ struct car* add_car(struct car* first,const char* target) { struct car* newcar = calloc(1,sizeof(struct car)); strcpy(newcar->value, target); + if (first == NULL) { + return newcar; + } struct car* this = first; while (this->next != NULL) { this = this->next; @@ -15,21 +18,41 @@ struct car* add_car(struct car* first,const char* target) { } void print_train(struct car* first) { - while(first != NULL){ - printf("%s", first->value); - first = first->next; + struct car* this = first; + while (this != NULL) { + printf("%s\n", this->value); + this = this->next; } } void cancel_train(struct car* first) { - while(first != NULL){ - free(first->next); - first = first->next; + struct car* this = first; + while (this != NULL) { + struct car* next_car = this->next; + free(this); + this = next_car; + } +} + + +struct car* clear_train(struct car* first, const char* name) { + struct car* this = first; + struct car* prev = NULL; + + while (this != NULL) { + if (strcmp(this->value, name) == 0) { + if (prev == NULL) { + struct car* temp = this->next; + free(this); + return clear_train(temp, name); + } else { + prev->next = this->next; + free(this); + return first; + } + } + prev = this; + this = this->next; } + return first; } - - -struct car* clear_train(struct car* first, const char* target) { - return NULL; -} -