usaa24/cv4/a_train.c

80 lines
1.6 KiB
C
Raw Normal View History

2024-10-17 17:45:46 +00:00
#include "a_train.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct car* add_car(struct car* first, const char* target) {
2024-10-17 17:49:18 +00:00
struct car* newcar = (struct car*)calloc(1, sizeof(struct car));
2024-10-17 17:45:46 +00:00
if (newcar == NULL) {
2024-10-17 17:49:18 +00:00
printf("Chyba: nepodarilo sa alokovať pamäť.\n");
2024-10-17 17:45:46 +00:00
exit(1);
}
2024-10-17 17:49:18 +00:00
strcpy(newcar->value, target);
newcar->next = NULL;
2024-10-17 17:45:46 +00:00
if (first == NULL) {
return newcar;
}
struct car* current = first;
while (current->next != NULL) {
current = current->next;
}
current->next = newcar;
return first;
}
void print_train(struct car* first) {
struct car* current = first;
if (current == NULL) {
2024-10-17 17:49:18 +00:00
printf("Vlak je prázdny.\n");
2024-10-17 17:45:46 +00:00
return;
}
while (current != NULL) {
2024-10-17 17:49:18 +00:00
printf("%s\n", current->value);
2024-10-17 17:45:46 +00:00
current = current->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* prev = NULL;
struct car* current = first;
while (current != NULL) {
if (strcmp(current->value, target) == 0) {
if (prev == NULL) {
struct car* temp = current->next;
free(current);
current = temp;
first = current;
} else {
prev->next = current->next;
free(current);
current = prev->next;
}
} else {
prev = current;
current = current->next;
}
}
2024-10-17 17:49:18 +00:00
2024-10-17 17:45:46 +00:00
return first;
}