123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- #include <err.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include "linked_list.h"
- LL_DEF(node, int x, float y);
- #define SHOW_NODE(ITEM) \
- ((ITEM) ? printf("%p is %d and %f\n", (ITEM), (ITEM)->x, (ITEM)->y) \
- : puts("None"))
- void
- append(node **list, int x, float y)
- {
- node *item;
- /* it is better to use `calloc`
- * otherwise you will need to set `LL_NEXT` to `NULL`
- */
- if (!(item = calloc(1, sizeof(*item))))
- errx(!0, "failed to allocate memory");
- item->x = x;
- item->y = y;
- /*
- * if you not used calloc:
- * LL_NEXT(item) = NULL;
- */
- LL_APPEND(*list, item);
- }
- int
- cmp(node *item, int x)
- {
- return !(item->x == x);
- }
- int
- main(void)
- {
- node *list = NULL, *list2 = NULL;
- printf("size of node: %ld\n", sizeof(node));
- for (int i = 0; i < 10; i++)
- append(&list, i, ((float)i) * 14.88);
- node *i;
- LL_FOREACH(list, i) SHOW_NODE(i);
- size_t len;
- LL_LENGTH(list, len);
- printf("list len: %ld\n", len);
- puts("----------------------------------");
- LL_FOREACH(list, i) append(&list2, i->x, i->y);
- puts("reversed");
- LL_REVERSE(list);
- LL_FOREACH(list, i) SHOW_NODE(i);
- puts("----------------------------------");
- LL_CONCAT(list, list2);
- LL_LENGTH(list, len);
- printf("list len: %ld\n", len);
- LL_FOREACH(list, i) SHOW_NODE(i);
- puts("----------------------------------");
- printf("search x == 5: ");
- LL_SEARCH(list, cmp, 5, i);
- SHOW_NODE(i);
- printf("search x == 1488: ");
- LL_SEARCH(list, cmp, 1488, i);
- SHOW_NODE(i);
- puts("----------------------------------");
- LL_FOREACH(list, i)
- {
- printf("deleting ");
- SHOW_NODE(i);
- LL_DELETE(list, i);
- free(i);
- }
- return 0;
- }
|