usaa25/du4/a_train.c
2025-10-28 20:30:24 +01:00

82 lines
1.6 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;
}
if(first->next->next == NULL && strcmp(first->value, target) == 0){
struct car* temp = first;
first = first->next;
first->next = NULL;
free(temp);
return first;
}
struct car* prev= NULL;
struct car* temp = first;
while (temp->next)
{
prev = temp;
temp = temp->next;
if(strcmp(temp->value, target) == 0){
prev->next = temp->next;
temp = prev->next;
}
}
return first;
}