usaa25/du4/a_train.c
2025-10-28 17:35:25 +01:00

75 lines
1.4 KiB
C

#include "a_train.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct car* add_car(struct car* first,const char* target) {
if(first == NULL){
first = calloc(1, sizeof(struct car));
strcpy(first->value, target);
return first;
}
struct car* temp = first;
while(temp->next){
temp = temp->next;
}
struct car* newCar = (struct car*)calloc(1, sizeof(struct car));
strcpy(newCar->value, target);
temp->next = newCar;
return first;
}
void print_train(struct car* first) {
struct car* temp = first;
while(temp){
printf("%s\n", temp->value);
temp = temp->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) {
if(first == NULL){
return NULL;
}
if (first->next == NULL && strcmp(first->value, target) == 0)
{
free(first);
return NULL;
}
else if(first->next == NULL && strcmp(first->value, target) != 0){
return first;
}
struct car* temp = first;
struct car* next = first->next;
while (next->next)
{if(strcmp(next->value, target) == 0){
temp->next = next->next;
free(next);
next = temp->next;
}
else{
temp = next;
next = next->next;}
}
return first;
}