1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#define LIST_TYPE(_name, _type) \
typedef struct _name { \
_type value; \
struct _name* next; \
} _name##_t;
#define LIST_NEW(_name, _type) \
static struct _name* _name##_new(_type v) { \
struct _name* l = malloc(sizeof(struct _name)); \
l->value = v; \
l->next = NULL; \
return l; \
}
#define LIST_CLEAR(_name, _type) \
static void _name##_clear(struct _name *l) { \
while (l) { \
struct _name *next = l->next; \
_name##_delete(l); \
l = next; \
} \
}
#define LIST_APPENDV(_name, _type) \
static void _name##_appendv(struct _name** list, _type v) { \
while (*list) { \
list = &(*list)->next; \
} \
*list = _name##_new(v); \
}
#define LIST_LEN(_name, _type) \
static int _name##_len(const struct _name* list) { \
int len = 0; \
while (list) { \
len++; \
list = list->next; \
} \
return len; \
}
#define LIST(_name, _type) \
LIST_TYPE(_name, _type) \
LIST_NEW(_name, _type) \
LIST_CLEAR(_name, _type) \
LIST_APPENDV(_name, _type) \
LIST_LEN(_name, _type)
LIST(float_list, float)
LIST(int_list, int)
int main(void) {
int_list_t* ilist = int_list_new(1);
int_list_appendv(&ilist, 2);
int_list_appendv(&ilist, 3);
float_list_t* flist = float_list_new(1.0f);
float_list_appendv(&flist, 2.0f);
float_list_appendv(&flist, 3.0f);
printf("%d\n", int_list_len(ilist)); // 3
printf("%d\n", float_list_len(flist)); // 3
float_list_clear(flist);
int_list_clear(ilist);
return 0;
} |
Partager