88 lines
2.1 KiB
C
88 lines
2.1 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <ctype.h>
|
|
|
|
#include "a_train.h"
|
|
|
|
struct car* add_car(struct car* first,const char* target) {
|
|
struct car* newcar = calloc(1, sizeof(struct car));
|
|
|
|
if(target == NULL){
|
|
return 0;
|
|
}
|
|
//if list is empty, then add newcar
|
|
if(first == NULL){
|
|
strcpy(newcar->value, target);
|
|
newcar->next = NULL;
|
|
return newcar;
|
|
}
|
|
strcpy(newcar->value,target);
|
|
newcar->next = NULL;
|
|
struct car *this = first;
|
|
|
|
//find the end of linked list
|
|
while(this->next != NULL){
|
|
this = this->next;
|
|
}
|
|
|
|
//add target in the end
|
|
this->next = newcar;
|
|
return first;
|
|
}
|
|
|
|
void print_train(struct car* first) {
|
|
for(struct car* this = first; this != NULL; this = this->next){
|
|
printf("%s\n", this->value);
|
|
}
|
|
}
|
|
|
|
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) {
|
|
if(first == NULL){
|
|
return 0;
|
|
}
|
|
//if there is only one element in linked list, than check if target and value are the same
|
|
if(first->next == NULL){
|
|
int result = strcmp(first->value, target);
|
|
if(result == 0){
|
|
free(first);
|
|
return 0;
|
|
}
|
|
else{
|
|
return first;
|
|
}
|
|
}
|
|
|
|
//check all the elemets in linked list
|
|
struct car* prev = first;
|
|
while(prev->next != NULL){
|
|
int x = strcmp(first->value, target);
|
|
//if the first element and target are the same
|
|
if(x == 0){
|
|
prev = first->next;
|
|
free(first);
|
|
return prev;
|
|
|
|
}
|
|
x = strcmp(prev->next->value, target);
|
|
//else check all other elements
|
|
if(x == 0){
|
|
struct car* third = prev->next->next;
|
|
free(prev->next);
|
|
prev->next = third;
|
|
return first;
|
|
|
|
}
|
|
prev = prev->next;
|
|
}
|
|
return first;
|
|
|
|
}
|