usaa25/du4/a_train.c
2025-12-01 12:15:34 +01:00

59 lines
1.4 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* new = calloc(1, sizeof(struct car));
if(!new) return first; // copirovanie cielvej stanice
strcpy(new->value,target);
if (first==NULL){
return new; // ak nebolo first, new bude prvy
}
struct car* sm = first;
while(sm->next!=NULL){
sm = sm->next;
}
sm->next = new; // pridavanie vozna na koniec
return first;
}
void print_train(struct car* first) {
struct car* hlp = first; //pomocna struktura
while(hlp!=NULL){ // ak je vozen
printf("Cielova stanica je %s\n",hlp->value); // vypis cielovych stanic voznov
hlp = hlp->next;
}
}
void cancel_train(struct car* first) {
if(!first) return;
cancel_train(first->next); // recursivna funkcia, ktora vymaze uplne vlak
free(first);
}
struct car* clear_train(struct car* first, const char* target) {
if(!first) return NULL;
if (strcmp(first->value, target)==0){
struct car* tmp = first->next;
free(first);
return tmp; // vrati to co bolo vymazane ak bol iba jeden vozen
}
struct car* hlp = first;
while (hlp->next!=NULL&&strcmp(hlp->next->value,target)!=0){
hlp = hlp->next; //hlada vozen
}
if (hlp->next!=NULL&&strcmp(hlp->next->value,target)==0){
struct car* del = hlp->next;
hlp->next=hlp->next->next; // spoji predchadzajuci a nasledujuci vozen
free(del); //vymaze vozen
}
return first; // link na zaciatok vlaku
}