Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // merge sightings of the same species on the same day
- // into the first sighting of the species on that day
- // The number of whales seen in subsequent sightings is added
- // to the number of whales seen in the first sighting.
- // The subsequent sightings are deleted from the list
- // and all associated memory freed.
- // compare equality of string 'species'
- int same_species(struct pod *pod, struct pod *comp) {
- return (strcmp(pod->species, comp->species) == 0);
- }
- // check dates are the same
- int same_day(struct date *day, struct date *comp) {
- return (day->year == comp->year &&
- day->month == comp->month &&
- day->day == comp->day);
- }
- // check same day and same date
- int same_day_species(struct pod *pod, struct pod *comp) {
- return (same_species(pod, comp) && same_day(pod->when, comp->when));
- }
- // delete a pod strct
- void delete_pod(struct pod *curr) {
- // don't delete if null
- if (!curr) return;
- free(curr->species);
- free(curr->when);
- free(curr);
- }
- // helper for main
- struct pod *merge_helper(struct pod *comp, struct pod *curr) {
- if (curr) {
- struct pod *next = curr->next;
- if (same_day_species(comp, curr)) {
- comp->how_many += curr->how_many;
- delete_pod(curr);
- curr = merge_helper(comp, next);
- } else {
- curr->next = merge_helper(comp, next);
- }
- }
- return curr;
- }
- // main
- void merge_day_whales(struct pod *first_pod) {
- struct pod *curr = first_pod;
- while (curr->next) {
- curr->next = merge_helper(curr, curr->next);
- curr = curr->next;
- }
- }
Add Comment
Please, Sign In to add comment