usaa24/cv4/a_train.c

114 lines
2.0 KiB
C
Raw Normal View History

2024-10-17 20:15:38 +00:00
#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)
{
2024-10-17 20:42:42 +00:00
if(!strcmp(target, first->value))
2024-10-17 20:15:38 +00:00
{
free(first);
2024-10-17 20:42:42 +00:00
//first = NULL;
2024-10-17 20:15:38 +00:00
return NULL;
}
else
{
return first;
}
}
struct car* prev = first;
2024-10-17 21:02:31 +00:00
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);
return first;
}
else
{
return first;
}
}
2024-10-17 20:15:38 +00:00
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;
}