usaa25/du5/a_station.c

108 lines
2.3 KiB
C

#include "a_station.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.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){
free(station->tracks);
free(station);
}
int select_track(struct station* station, const char* target){
unsigned int hash = 0;
for (int i = 0; i < strlen(target); i++)
{ hash += target[i] + (hash<<6) + (hash<<16) - hash;
}
hash = hash %station->track_count;
return hash;
}
void add_target_capacity(struct station* station,const char* target, int capacity){
int res = select_track(station, target);
struct car* previous = NULL;
struct car** ptr = &station->tracks[res];
struct car* head = *ptr;
while(head){
if(strcmp(head->value, target) == 0){
head->capacity += capacity;
return;
}
previous = head;
head = head->next;
}
struct car* next = (struct car*)calloc(1, sizeof(struct car));
strcpy(next->value, target);
next->capacity = capacity;
if(previous){
previous->next = next;
}
else{
*ptr = next;
}
}
int get_target_capacity(struct station* station,const char* target){
int res = select_track(station, target);
struct car** ptr = &station->tracks[res];
struct car* head = *ptr;
while (head)
{if(strcmp(head->value, target) == 0){
return head->capacity;
}
head = head->next;
}
return 0;
}
int count_targets(struct station* station){
if(station == NULL || station->tracks == NULL){
return 0;
}
int total = 0;
for(int i = 0; i<station->track_count; i++){
struct car* ptr = station->tracks[i];
while(ptr){
total++;
ptr = ptr->next;
}
}
return total;
}
int count_capacity(struct station* station){
if(station == NULL || station->tracks == NULL){
return 0;
}
int total = 0;
for(int i = 0; i<station->track_count; i++){
struct car* ptr = station->tracks[i];
while(ptr){
total += ptr->capacity;
ptr = ptr->next;
}
}
return total;
}