diff --git a/du5/a_station.c b/du5/a_station.c index 1b4da0c..7c62bf4 100644 --- a/du5/a_station.c +++ b/du5/a_station.c @@ -28,56 +28,34 @@ int select_track(struct station* station, const char* target){ } void add_target_capacity(struct station* station,const char* target, int capacity){ - struct car* ptr = *station->tracks; - int count = 0; - int res = select_track(station, target); - while(ptr){ - if(count == res){ - break; - } - if (strcmp(ptr->value, target) ==0 ){ - ptr->capacity += 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; - ptr = ptr->next; - count++; + head = head->next; + } - if(count < res){ - struct car* next = (struct car*)calloc(1, sizeof(struct car)); - strcpy(next->value, target); - next->capacity = capacity; - if(ptr){ - ptr->next = next; - return;} - else{ - *station->tracks = next; - return; - } + struct car* next = (struct car*)calloc(1, sizeof(struct car)); + strcpy(next->value, target); + next->capacity = capacity; + if(previous){ + previous->next = next; } - else if (count == res && ptr && strcmp(ptr->value, target) != 0){ - struct car* next = (struct car*)calloc(1, sizeof(struct car)); - strcpy(next->value, target); - next->capacity = capacity; - if(ptr){ - ptr->next = next; - return;} - else{ - *station->tracks = next; - return; - } - - + else{ + *ptr = next; } - if (!ptr){ - return; - } - ptr->capacity += capacity; - return; +} -} int get_target_capacity(struct station* station,const char* target){ struct car* ptr = *station->tracks; @@ -109,9 +87,13 @@ int count_targets(struct station* station){ } int count_capacity(struct station* station){ - int total = 0; -for (struct car* ptr = *station->tracks; ptr; ptr = ptr->next) - total += ptr->capacity; -return total; + int res = 0; + struct car* ptr = *station->tracks; + while (ptr){ + res += ptr->capacity; + ptr = ptr->next; + + } + return res; }