#include "a_station.h" struct station* create_station() { struct station* s = calloc(1, sizeof(struct station)); s->tracks = calloc(STATION_SIZE, sizeof(struct car*)); s->track_count = STATION_SIZE; return s; } int select_track(struct station* s, const char* target) { unsigned long hash = 5381; //5381 это алгоритм DJB2 int c; while ((c = *target++)) { // не забываем ++ чтобы идти по строке hash = ((hash << 5) + hash) + c; //hash << 5 сдвигает все биты числа hash на 5 позиций влево. Это тоже самое, что умножить на 2 в пятой степени } return (int)(hash % s->track_count); } void add_target_capacity(struct station* s, const char* target, int capacity) { if (!s || !target) { return; } int index = select_track(s, target); struct car* current = s->tracks[index]; if (current == NULL) { //Этот кусок кода создаёт “поезд” на пустой колее. struct car* new_car = calloc(1, sizeof(struct car)); strcpy(new_car->value, target); new_car->capacity = capacity; new_car->next = NULL; s->tracks[index] = new_car; return; } struct car* prev = NULL; //создаём указатель prev, который будет хранить предыдущий элемент списка while (current != NULL) { if (strcmp(current->value, target) == 0) { current->capacity += capacity; return; } prev = current; current = current->next; } struct car* new_car = calloc(1, sizeof(struct car)); strcpy(new_car->value, target); new_car->capacity = capacity; new_car->next = NULL; prev->next = new_car; } struct car* find_target(struct station* s, const char* target) { if (!s || !target) return NULL; int index = select_track(s, target); struct car* current = s->tracks[index]; while (current != NULL) { if (strcmp(current->value, target) == 0) { return current; } current = current->next; } return NULL; } int get_total_targets(struct station* s) { if (!s) return 0; int count = 0; for (int i = 0; i < s->track_count; i++) { struct car* current = s->tracks[i]; while (current != NULL) { count++; current = current->next; } } return count; } int get_total_capacity(struct station* s) { if (!s) return 0; int total = 0; for (int i = 0; i < s->track_count; i++) { struct car* current = s->tracks[i]; while (current != NULL) { total += current->capacity; current = current->next; } } return total; } void print_station(struct station* s) { if (!s) return; printf("station>>>\n"); for (int i = 0; i < s->track_count; i++) { struct car* current = s->tracks[i]; printf("[%d]: ", i); while (current != NULL) { printf("%s (%d) -> ", current->value, current->capacity); current = current->next; } printf("NULL\n"); } printf("<<track_count; i++) { struct car* current = s->tracks[i]; while (current != NULL) { struct car* to_delete = current; current = current->next; free(to_delete); } } free(s->tracks) free(s); }