usaa21/cv4/a_train.c

81 lines
1.5 KiB
C
Raw Normal View History

2021-11-04 19:08:37 +00:00
#include "a_train.h"
#include <stdio.h>
2021-11-04 19:12:23 +00:00
#include <string.h>
#include <stdlib.h>
2021-11-04 19:08:37 +00:00
struct car* add_car(struct car* first,const char* target) {
2021-11-04 19:12:23 +00:00
struct car* new_car = (struct car*)calloc(1,sizeof(struct car));
2021-11-04 19:08:37 +00:00
strcpy(new_car->value, target);
new_car->next = NULL;
if (first == NULL){
first = new_car;
}
else {
struct car* temp=first;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = new_car;
}
return first;
}
void print_train(struct car* first) {
struct car* this = first;
while(this != NULL){
2021-11-05 07:17:02 +00:00
printf("%s->",this->value);
2021-11-04 19:08:37 +00:00
this = this->next;
}
}
void cancel_train(struct car* first) {
if (first != NULL){
cancel_train(first->next);
free(first);
}
}
struct car* clear_train(struct car* first, const char* target) {
struct car* this = first;
2021-11-04 19:14:54 +00:00
if (this == NULL){
return NULL;
}
2021-11-04 19:36:08 +00:00
if (this->next == NULL){
2021-11-04 19:17:06 +00:00
if(strcmp(this->value, target) == 0){
free(this);
return NULL;
}else {
2021-11-04 19:38:28 +00:00
return this;
2021-11-04 19:17:06 +00:00
}
2021-11-04 19:36:08 +00:00
}
2021-11-04 19:08:37 +00:00
while( this->next->next != NULL){
2021-11-05 07:44:18 +00:00
if(strcmp(this->value, target) == 0){
struct car* tmp = this->next;
free(this);
return tmp;
}
else if(strcmp(this->next->value, target) == 0){
2021-11-04 19:56:24 +00:00
struct car* third = this->next->next;
2021-11-04 19:20:56 +00:00
free(this->next);
2021-11-04 19:56:24 +00:00
this->next = third;
2021-11-04 19:38:28 +00:00
return this;
2021-11-04 19:18:56 +00:00
}
else {
2021-11-04 19:29:11 +00:00
this = this->next;
2021-11-04 19:08:37 +00:00
}
2021-11-04 20:05:56 +00:00
}
2021-11-05 07:38:35 +00:00
if(strcmp(this->value, target) == 0){
struct car* tmp = this->next;
free(this);
return tmp;
}else if(strcmp(this->next->value, target) == 0){
2021-11-04 20:05:56 +00:00
free(this->next);
2021-11-05 07:38:35 +00:00
this->next=NULL;
2021-11-05 07:41:35 +00:00
return first;
2021-11-04 19:08:37 +00:00
}
2021-11-04 19:46:01 +00:00
return first;
2021-11-04 19:08:37 +00:00
}