#include #include #include #include "list.h" typedef struct { int hp; list_t node; char *name; } champion_t; static void print_champs(const char *msg, const list_t *champs) { const list_t *node; printf("%s\n", msg); list_for_each(node, champs) { const champion_t *champ = list_entry(node, champion_t, node); printf("name:%s hp:%d\n", champ->name, champ->hp); } } static champion_t *new_champ(const char *name, const int hp) { champion_t *champ = (champion_t *)malloc(sizeof(*champ)); champ->name = (char *)malloc(strlen(name) + 1); champ->hp = hp; strcpy(champ->name, name); list_init(&champ->node); return champ; } static void add_champ(champion_t *champ, list_t *list) { list_add(&champ->node, list); } static void del_champ(champion_t *champ) { list_del(&champ->node); } static void swab_champ(champion_t *a, champion_t *b) { champion_t tmp; tmp = *b; b->hp = a->hp; b->name = a->name; a->hp = tmp.hp; a->name = tmp.name; } static void destroy_champs(list_t *champs) { while (!list_is_empty(champs)) { champion_t *champ = list_entry(champs->next, champion_t, node); del_champ(champ); free(champ->name); free(champ); } } static void sort_champs(list_t *champs, int (*cmp)(const void *, const void *)) { list_t *node_m, *node_s; list_for_each(node_m, champs) { champion_t *champ_m = list_entry(node_m, champion_t, node); champion_t *champ_this = champ_m; list_for_each(node_s, node_m) { if (node_s == champs) break; champion_t *champ_s = list_entry(node_s, champion_t, node); if (cmp(champ_this, champ_s) >= 0) champ_this = champ_s; } swab_champ(champ_m, champ_this); } } static int compare_hp(const void *_a, const void *_b) { const champion_t *a = (const champion_t *)_a; const champion_t *b = (const champion_t *)_b; return a->hp - b->hp; } static int compare_name(const void *_a, const void *_b) { const champion_t *a = (const champion_t *)_a; const champion_t *b = (const champion_t *)_b; return strcmp(a->name, b->name); } int main(void) { list_t champions; list_init(&champions); add_champ(new_champ("abc", 10), &champions); add_champ(new_champ("ghi", 5), &champions); add_champ(new_champ("def", 20), &champions); print_champs("--list--", &champions); sort_champs(&champions, compare_hp); print_champs("--by hp--", &champions); sort_champs(&champions, compare_name); print_champs("--by name--", &champions); destroy_champs(&champions); return 0; }