81 lines
2.5 KiB
C
81 lines
2.5 KiB
C
|
#include <inttypes.h>
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <stdint.h>
|
||
|
|
||
|
#define DEFINE_LIST(type) \
|
||
|
struct list_##type { \
|
||
|
type value; \
|
||
|
struct list_##type *next; \
|
||
|
}; \
|
||
|
struct list_##type *list_##type##_create(type value) { \
|
||
|
struct list_##type *list = (void *) malloc(sizeof(struct list_##type)); \
|
||
|
if (list == NULL) \
|
||
|
return NULL; \
|
||
|
list->value = value; \
|
||
|
list->next = NULL; \
|
||
|
return list; \
|
||
|
} \
|
||
|
void list_##type##_free(struct list_##type *list) { \
|
||
|
struct list_##type *temp; \
|
||
|
while (list != NULL) { \
|
||
|
temp = list; \
|
||
|
list = list->next; \
|
||
|
free(temp); \
|
||
|
} \
|
||
|
} \
|
||
|
void list_##type##_push(struct list_##type *list, type value) { \
|
||
|
if (list == NULL) return;
|
||
|
while (list->next != NULL) list = list->next; \
|
||
|
struct list_##type *item = list_##type##_create(value); \
|
||
|
list->next = item; \
|
||
|
} \
|
||
|
void list_##type##_print(struct list_##type *list, char* format) { \
|
||
|
while (list != NULL) { \
|
||
|
printf(format, list->value); \
|
||
|
list = list->next; \
|
||
|
} \
|
||
|
printf("\n"); \
|
||
|
}
|
||
|
|
||
|
#define list_create(value) \
|
||
|
_Generic((value), \
|
||
|
int64_t : list_int64_t_create(value), \
|
||
|
double : list_double_create(value), \
|
||
|
default : printf("This type is not supported\n"))
|
||
|
|
||
|
#define list_free(list) \
|
||
|
_Generic((list), \
|
||
|
struct list_int64_t : list_int64_t_free(list), \
|
||
|
struct list_double : list_double_free(list), \
|
||
|
default : printf("This type is not supported\n"))
|
||
|
|
||
|
#define list_push(list, value) \
|
||
|
_Generic((value), \
|
||
|
int64_t : list_int64_t_push(list, value), \
|
||
|
double : list_double_push(list, value), \
|
||
|
default : printf("This type is not supported\n"))
|
||
|
|
||
|
#define list_print(list) \
|
||
|
_Generic((*list), \
|
||
|
struct list_int64_t : list_int64_t_print(list, "%d "), \
|
||
|
struct list_double : list_double_print(list, "%lf "), \
|
||
|
default : printf("This type is not supported\n"))
|
||
|
|
||
|
DEFINE_LIST(int64_t);
|
||
|
DEFINE_LIST(double);
|
||
|
|
||
|
int main() {
|
||
|
struct list_int64_t *list = list_create((int64_t) 5);
|
||
|
list_push(list, (int64_t) 2);
|
||
|
list_push(list, (int64_t) 1);
|
||
|
list_print(list);
|
||
|
|
||
|
struct list_double *list2 = list_create((double) 2.2);
|
||
|
list_push(list2, (double) 0.1);
|
||
|
list_push(list2, (double) 5.7);
|
||
|
list_print(list2);
|
||
|
|
||
|
return 0;
|
||
|
}
|