usaa24/cv4/a_train.c

64 lines
1.7 KiB
C
Raw Permalink Normal View History

2024-10-24 22:04:05 +00:00
#include "a_train.h"
#include <stdio.h>
2024-10-24 22:16:27 +00:00
#include <stdlib.h>
#include <string.h>
2024-10-24 22:04:05 +00:00
2024-10-24 22:16:27 +00:00
// Додаємо вагон в кінець списку
struct car* add_car(struct car* first, const char* target) {
struct car* newcar = (struct car*)calloc(1, sizeof(struct car));
if (newcar == NULL) {
return first;
}
strcpy(newcar->value, target);
if (first == NULL) {
return newcar;
}
struct car* this = first;
while (this->next != NULL) {
this = this->next;
}
this->next = newcar;
return first;
2024-10-24 22:04:05 +00:00
}
2024-10-24 22:16:27 +00:00
// Виводимо всі вагони (назви станцій)
2024-10-24 22:04:05 +00:00
void print_train(struct car* first) {
2024-10-24 22:16:27 +00:00
struct car* this = first;
while (this != NULL) {
printf("Station: %s\n", this->value);
this = this->next;
}
2024-10-24 22:04:05 +00:00
}
2024-10-24 22:16:27 +00:00
// Видаляємо весь список (звільняємо пам'ять)
2024-10-24 22:04:05 +00:00
void cancel_train(struct car* first) {
2024-10-24 22:16:27 +00:00
struct car* this = first;
while (this != NULL) {
struct car* next = this->next;
free(this);
this = next;
}
2024-10-24 22:04:05 +00:00
}
2024-10-24 22:16:27 +00:00
// Видаляємо всі вагони з певною станцією
2024-10-24 22:04:05 +00:00
struct car* clear_train(struct car* first, const char* target) {
2024-10-24 22:16:27 +00:00
struct car* prev = NULL;
struct car* this = first;
while (this != NULL) {
if (strcmp(this->value, target) == 0) {
if (prev == NULL) {
first = this->next;
free(this);
this = first;
} else {
prev->next = this->next;
free(this);
this = prev->next;
}
} else {
prev = this;
this = this->next;
}
}
return first;
}