usaa24/cv4/a_train.c

81 lines
1.9 KiB
C
Raw Permalink Normal View History

2024-10-24 15:49:05 +00:00
#include "a_train.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
2024-11-19 14:48:04 +00:00
// Добавление вагона в конец списка
2024-10-24 15:49:05 +00:00
struct car* add_car(struct car* first, const char* target) {
struct car* new_car = (struct car*)malloc(sizeof(struct car));
if (!new_car) {
return first;
}
strncpy(new_car->value, target, SIZE);
new_car->value[SIZE - 1] = '\0';
new_car->next = NULL;
if (first == NULL) {
return new_car;
}
struct car* current = first;
while (current->next != NULL) {
current = current->next;
}
current->next = new_car;
return first;
}
2024-11-19 14:48:04 +00:00
// Вывод содержимого поезда
2024-10-24 15:49:05 +00:00
void print_train(struct car* first) {
struct car* current = first;
if (current == NULL) {
2024-11-19 14:48:04 +00:00
printf("The train is empty.\n");
2024-10-24 15:49:05 +00:00
return;
}
2024-11-19 14:48:04 +00:00
printf("Train composition:\n");
2024-10-24 15:49:05 +00:00
while (current != NULL) {
printf("%s\n", current->value);
current = current->next;
}
}
2024-11-19 14:48:04 +00:00
// Удаление всех вагонов, освобождение памяти
2024-10-24 15:49:05 +00:00
void cancel_train(struct car* first) {
struct car* current = first;
while (current != NULL) {
struct car* next = current->next;
free(current);
current = next;
}
}
2024-11-19 14:48:04 +00:00
// Удаление вагонов с заданным направлением
2024-10-24 15:49:05 +00:00
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;
}