usaa24/cv4/a_train.c
2024-10-18 00:10:53 +02:00

151 lines
2.8 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;
struct car* bef_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* second = prev->next;
free(prev);
first = second;
return first;
}
else if(!strcmp(prev->next->value, target))
{
struct car* third = prev->next->next;
free(prev->next);
prev->next = third;
return first;
}
if(prev->next->next != NULL)
{
bef_prev = prev;
}
prev = prev->next;
}
if(prev->next->next == NULL)
{
if(!strcmp(prev->value, target))
{
struct car* last = prev->next;
free(prev);
bef_prev->next = last;
return first;
}
else if(!strcmp(prev->next->value, target))
{
free(prev->next);
prev->next = NULL;
return first;
}
else
{
return first;
}
}
return first;
}