usaa25/du4/a_train.c
2025-11-25 21:22:09 +01:00

90 lines
2.4 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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* novyj_vagon = (struct car*) malloc(sizeof(struct car)); // создаём новый вагон
if (novyj_vagon == NULL) {
printf("Chyba: nepodarilo sa vytvorit novy vozen!\n");
return first;
}
strncpy(novyj_vagon->value, target, SIZE - 1);
novyj_vagon->value[SIZE - 1] = '\0';
novyj_vagon->next = NULL; //Устанавливаем, что у нового вагона нет следующего
if (first == NULL) {
return novyj_vagon;
}
struct car* actual = first;//указатель для прохода по списку.
while (actual->next != NULL) {
actual = actual->next;
}
actual->next = novyj_vagon;
return first; //Возвращаем неизменённый первый элемент
}
void print_train (struct car* first) {
if (first == NULL) {
printf("vlak je prazdny!\n");
return;
}
struct car* actual = first;
int schet = 1;
while (actual != NULL) {
printf("%d. [%s]", schet, actual->value);
if (actual->next != NULL) {
printf(" -> ");
}
actual = actual->next;
schet++;
}
printf("\n");
}
void cancel_train (struct car* first) {
struct car* current = first;
while (current !=NULL) {
struct car* next_one = current->next;// запоминаем следующий вагон
memset(current->value, 0, SIZE); //Очищаем содержимое value
free(current);
current = next_one;; // переходим к следующему вагону
}
}
struct car* clear_train(struct car* first, const char* target) {
struct car* current = first;
struct car* previous = NULL;
while (current != NULL) {
if (strcmp(current->value, target) == 0) {
struct car* to_delete = current;
if (previous == NULL) {
first = current->next;
current = first;
}
else {
previous->next = current->next;
current = previous->next;
}
free(to_delete);
}
else {
previous = current;
current = current->next;
}
}
return first;
}