150 lines
2.0 KiB
C
150 lines
2.0 KiB
C
|
#include "a_train.h"
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
int getLength(struct car* first) {
|
||
|
|
||
|
if (first != NULL) {
|
||
|
|
||
|
int count = 1;
|
||
|
|
||
|
while (first->next != NULL) {
|
||
|
|
||
|
count++;
|
||
|
first = first->next;
|
||
|
|
||
|
}
|
||
|
|
||
|
return count;
|
||
|
|
||
|
} else {
|
||
|
|
||
|
return 0;
|
||
|
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
struct car* getLast(struct car* first) {
|
||
|
|
||
|
if (first == NULL) return NULL;
|
||
|
|
||
|
while (first->next != NULL) first = first->next;
|
||
|
|
||
|
return first;
|
||
|
|
||
|
}
|
||
|
|
||
|
struct car* getLastButOne(struct car* first) {
|
||
|
|
||
|
if (first == NULL || first->next == NULL) return NULL;
|
||
|
|
||
|
while (first->next->next != NULL) first = first->next;
|
||
|
|
||
|
return first;
|
||
|
|
||
|
}
|
||
|
|
||
|
struct car* add_car(struct car* first, const char* target) {
|
||
|
|
||
|
struct car* newcar = calloc(1,sizeof(struct car));
|
||
|
|
||
|
strcpy(newcar->value, target);
|
||
|
newcar->next = NULL;
|
||
|
|
||
|
if (first == NULL) return newcar;
|
||
|
|
||
|
struct car* last = getLast(first);
|
||
|
|
||
|
last->next = newcar;
|
||
|
|
||
|
return first;
|
||
|
|
||
|
}
|
||
|
|
||
|
void print_train(struct car* first) {
|
||
|
|
||
|
if (first == NULL) return;
|
||
|
|
||
|
struct car* this = first;
|
||
|
|
||
|
printf("\nTrain way:\n\n");
|
||
|
printf("%s", this->value);
|
||
|
|
||
|
while (this->next != NULL) {
|
||
|
|
||
|
this = this->next;
|
||
|
printf(" -> ");
|
||
|
printf("%s", this->value);
|
||
|
|
||
|
}
|
||
|
|
||
|
printf("\n\n");
|
||
|
|
||
|
}
|
||
|
|
||
|
void popBack(struct car* first) {
|
||
|
|
||
|
if (first == NULL) { printf("123"); return; }
|
||
|
|
||
|
struct car* lastbo = getLastButOne(first);
|
||
|
|
||
|
if (lastbo == NULL) {
|
||
|
|
||
|
free(first);
|
||
|
first = NULL;
|
||
|
|
||
|
} else {
|
||
|
|
||
|
free(lastbo->next);
|
||
|
lastbo->next = NULL;
|
||
|
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
void cancel_train(struct car* first) {
|
||
|
|
||
|
if (first == NULL) return;
|
||
|
|
||
|
while (first->next != NULL) popBack(first);
|
||
|
|
||
|
free(first);
|
||
|
first = NULL;
|
||
|
|
||
|
}
|
||
|
|
||
|
struct car* clear_train(struct car* first, const char* target) {
|
||
|
|
||
|
if (first == NULL) return NULL;
|
||
|
|
||
|
// while (first->next->next != NULL) {
|
||
|
|
||
|
// if (strcmp(first->next->value, target) == 0) {
|
||
|
|
||
|
// struct car* node = first->next->next;
|
||
|
|
||
|
// free(first->next);
|
||
|
|
||
|
// first->next = node;
|
||
|
|
||
|
// }
|
||
|
|
||
|
// }
|
||
|
|
||
|
struct car* this = first;
|
||
|
|
||
|
if (strcmp(first->value, target) == 0) {
|
||
|
|
||
|
this = this->next;
|
||
|
|
||
|
free(first);
|
||
|
|
||
|
}
|
||
|
|
||
|
return this;
|
||
|
|
||
|
}
|
||
|
|