pvjc26/du6/a_station.c
2026-04-23 14:19:46 +00:00

108 lines
2.7 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "a_station.h"
#include <stdlib.h>
#include <string.h>
// створення станції (у тебе вже добре зроблено)
struct station* create_station(){
struct station* station = (struct station*)calloc(1,sizeof(struct station));
station->tracks = (struct car**)calloc(STATION_SIZE, sizeof(struct car*));
station->track_count = STATION_SIZE;
return station;
}
// звільнення пам'яті
void destroy_station(struct station* station){
for(int i = 0; i < station->track_count; i++){
struct car* cur = station->tracks[i];
while(cur != NULL){
struct car* tmp = cur;
cur = cur->next;
free(tmp);
}
}
free(station->tracks);
free(station);
}
// проста хеш-функція
int select_track(struct station* station, const char* target){
int sum = 0;
for(int i = 0; target[i] != '\0'; i++){
sum += target[i];
}
return sum % station->track_count;
}
// додавання або оновлення
void add_target_capacity(struct station* station,const char* target, int capacity){
int index = select_track(station, target);
struct car* cur = station->tracks[index];
// шукаємо існуючий запис
while(cur != NULL){
if(strcmp(cur->value, target) == 0){
cur->capacity += capacity;
return;
}
cur = cur->next;
}
// якщо нема — створюємо новий
struct car* new_car = (struct car*)malloc(sizeof(struct car));
strcpy(new_car->value, target);
new_car->capacity = capacity;
new_car->next = station->tracks[index];
station->tracks[index] = new_car;
}
// отримати капацитет
int get_target_capacity(struct station* station,const char* target){
int index = select_track(station, target);
struct car* cur = station->tracks[index];
while(cur != NULL){
if(strcmp(cur->value, target) == 0){
return cur->capacity;
}
cur = cur->next;
}
return 0;
}
// кількість станцій
int count_targets(struct station* station){
int count = 0;
for(int i = 0; i < station->track_count; i++){
struct car* cur = station->tracks[i];
while(cur != NULL){
count++;
cur = cur->next;
}
}
return count;
}
// загальна кількість пасажирів
int count_capacity(struct station* station){
int sum = 0;
for(int i = 0; i < station->track_count; i++){
struct car* cur = station->tracks[i];
while(cur != NULL){
sum += cur->capacity;
cur = cur->next;
}
}
return sum;
}