usaa24/cv4/a_train.c
2024-11-18 14:43:38 +01:00

71 lines
1.6 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 = calloc(1, sizeof(struct car));
strcpy(newcar->value, target);
newcar->next = NULL;
if (first == NULL) {
first = newcar;
} else {
struct car* current = first;
while (current->next != NULL) {
current = current->next;
}
current->next = newcar;
}
return first;
}
void print_train(struct car* first) {
if(first != NULL){
struct car* current = first;
while(current != NULL){
printf("%s\n", current->value);
current = current->next;
}
}
}
void cancel_train(struct car* first) {
struct car* current = first;
while(first != NULL){
current = current->next;
free(first);
first = current;
}
}
struct car* clear_train(struct car* first, const char* target) {
if (first == NULL) {
return NULL;
}
struct car* current = first;
struct car* previous = NULL;
while (current != NULL && strcmp(current->value, target) == 0) {
struct car* temp = current;
first = current->next;
current = first;
free(temp);
}
while (current != NULL) {
if (strcmp(current->value, target) == 0) {
previous->next = current->next;
free(current);
current = previous->next;
} else {
previous = current;
current = current->next;
}
}
return first;
}