usaa24/cv4/a_train.c
2024-10-17 23:08:28 +02:00

115 lines
2.0 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);
if(first == NULL)
{
return newcar;
}
struct car* this = first;
while(this->next != NULL)
{
this = this->next;
}
this->next = newcar;
return first;
}
void print_train(struct car* first)
{
if(first == NULL)
{
return;
}
struct car* this = first;
while(this->next != NULL)
{
printf("%s\n", this->value);
this = this->next;
}
printf("%s\n", this->value);
}
void cancel_train(struct car* first)
{
if(first == NULL)
{
return;
}
struct car* this = first;
if(this->next != NULL)
{
cancel_train(this->next);
}
free(first);
}
struct car* clear_train(struct car* first, const char* target)
{
if(first == NULL)
{
return NULL;
}
if(first->next == NULL)
{
if(!strcmp(target, first->value))
{
free(first);
//first = NULL;
return NULL;
}
else
{
return first;
}
}
struct car* prev = first;
if(prev->next->next == NULL)
{
if(!strcmp(prev->value, target))
{
struct car* second = prev->next;
free(prev);
first = second;
return first;
}
else if(!strcmp(prev->next->value, target))
{
free(prev->next);
prev->next = NULL;
return first;
}
else
{
return first;
}
}
while (prev->next->next != NULL)
{
if(strcmp(prev->value, target))
{
struct car* third = prev->next->next;
free(prev->next);
prev->next = third;
return first;
}
prev = prev->next;
}
return first;
}