64 lines
1.7 KiB
C
64 lines
1.7 KiB
C
#include "a_train.h"
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
// Додаємо вагон в кінець списку
|
|
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;
|
|
}
|
|
|
|
// Виводимо всі вагони (назви станцій)
|
|
void print_train(struct car* first) {
|
|
struct car* this = first;
|
|
while (this != NULL) {
|
|
printf("Station: %s\n", this->value);
|
|
this = this->next;
|
|
}
|
|
}
|
|
|
|
// Видаляємо весь список (звільняємо пам'ять)
|
|
void cancel_train(struct car* first) {
|
|
struct car* this = first;
|
|
while (this != NULL) {
|
|
struct car* next = this->next;
|
|
free(this);
|
|
this = next;
|
|
}
|
|
}
|
|
|
|
// Видаляємо всі вагони з певною станцією
|
|
struct car* clear_train(struct car* first, const char* target) {
|
|
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;
|
|
} |