単連結リストの整列 #100 二教科の成績の保持体の実装
インタフェイスを実装する。
school_record.c
#include <stdlib.h> #include <string.h> #include "school_record.h" struct tag_school_record { char *name; const grade_t *maths; const grade_t *physics; }; typedef enum { EGRADE_A = 5, EGRADE_B = 4, EGRADE_C = 3 } egrade_t; struct tag_grade { egrade_t grade; }; static grade_t grades[] = {{EGRADE_A}, {EGRADE_B}, {EGRADE_C}}; const grade_t * const GRADE_A = &grades[0]; const grade_t * const GRADE_B = &grades[1]; const grade_t * const GRADE_C = &grades[2]; school_record_t *school_record_new(const char *name, const grade_t *maths, const grade_t *physics) { school_record_t *p = NULL; if (name != NULL) { p = malloc(sizeof(school_record_t)); if (p != NULL) { p->name = malloc(strlen(name) + 1); if (p->name != NULL) { strcpy(p->name, name); p->maths = maths; p->physics = physics; } else { free(p); } } } return p; } void school_record_dispose(school_record_t *rec) { free(rec->name); free(rec); } const char *school_record_get_name(const school_record_t *rec) { return rec->name; } const grade_t *school_record_get_maths(const school_record_t *rec) { return rec->maths; } const grade_t *school_record_get_physics(const school_record_t *rec) { return rec->physics; } int grade_compare(const grade_t *g1, const grade_t *g2) { if (g1->grade > g2->grade) return 1; else if (g1->grade == g2->grade) return 0; else return -1; }
特に工夫も何もなく。