usaa24/cv4/a_train.c

73 lines
1.6 KiB
C
Raw Normal View History

2024-10-15 12:34:20 +00:00
#include "a_train.h"
#include <stdio.h>
2024-10-15 13:43:00 +00:00
#include <stdlib.h>
#include <string.h>
2024-10-15 12:34:20 +00:00
2024-10-20 12:58:05 +00:00
struct car* add_car(struct car* first, const char* target) {
2024-10-15 13:43:00 +00:00
struct car* last = first;
2024-10-20 12:58:05 +00:00
struct car* newcar = calloc(1, sizeof(struct car));
2024-10-15 13:43:00 +00:00
strcpy(newcar->value, target);
2024-10-20 12:58:05 +00:00
if (last != NULL) {
2024-10-15 13:43:00 +00:00
struct car* current = last;
2024-10-20 12:58:05 +00:00
while (current->next != NULL) {
current = current->next;
2024-10-15 13:43:00 +00:00
}
current->next = newcar;
2024-10-20 12:58:05 +00:00
} else {
2024-10-15 13:43:00 +00:00
last = newcar;
return last;
}
2024-10-20 12:58:05 +00:00
2024-10-15 13:43:00 +00:00
return first;
2024-10-15 12:34:20 +00:00
}
void print_train(struct car* first) {
2024-10-20 12:59:11 +00:00
if(first != NULL){
struct car* current = first;
while(current->next != NULL){
printf("%s\n", current->value);
current = current->next;
}
}
2024-10-15 12:34:20 +00:00
}
void cancel_train(struct car* first) {
2024-10-20 13:06:03 +00:00
struct car* current = first;
while(first != NULL){
current = current->next;
free(first);
first = current;
}
2024-10-15 12:34:20 +00:00
}
struct car* clear_train(struct car* first, const char* target) {
2024-10-20 13:06:03 +00:00
if (first == NULL) {
2024-10-20 13:00:06 +00:00
return NULL;
}
2024-10-20 13:06:03 +00:00
struct car* current = first;
struct car* previous = NULL;
while (current != NULL && strcmp(current->value, target) == 0) {
struct car* temp = current;
first = current->next;
current = first;
free(temp);
2024-10-20 13:00:06 +00:00
}
2024-10-15 13:43:00 +00:00
2024-10-20 13:06:03 +00:00
while (current != NULL) {
2024-10-20 13:02:50 +00:00
if (strcmp(current->value, target) == 0) {
2024-10-20 13:06:03 +00:00
previous->next = current->next;
2024-10-20 13:00:06 +00:00
free(current);
2024-10-20 13:06:03 +00:00
current = previous->next;
2024-10-20 13:00:06 +00:00
} else {
2024-10-20 13:06:03 +00:00
previous = current;
current = current->next;
2024-10-20 13:00:06 +00:00
}
}
2024-10-15 12:34:20 +00:00
2024-10-20 13:06:03 +00:00
return first;
}