usaa25/du4/a_train.c
2025-11-06 17:57:19 +01:00

60 lines
1.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "a_train.h"
struct car* add_car(struct car* first, const char* target) {
struct car* newcar = calloc(1, sizeof(struct car));
if (newcar == NULL) {
return first;
}
strcpy(newcar->value, target);
newcar->next = NULL;
if (first == NULL) {
return newcar;
}
struct car* this = first;
while (this->next != NULL) {
this = this->next;
}
this->next = newcar;
return first;
}
void print_train(struct car* first) {
struct car* this = first;
while (this != NULL) {
printf("%s\n", this->value);
this = this->next;
}
}
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* target) {
struct car* current = first;
struct car* prev = NULL;
while (current != NULL) {
if (strcmp(current->value, target) == 0) {
struct car* to_delete = current;
if (prev == NULL) {
first = current->next;
} else {
prev->next = current->next;
}
current = current->next;
free(to_delete);
} else {
prev = current;
current = current->next;
}
}
return first;
}