test.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <err.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include "linked_list.h"
  5. LL_DEF(node, int x, float y);
  6. #define SHOW_NODE(ITEM) \
  7. ((ITEM) ? printf("%p is %d and %f\n", (ITEM), (ITEM)->x, (ITEM)->y) \
  8. : puts("None"))
  9. void
  10. append(node **list, int x, float y)
  11. {
  12. node *item;
  13. /* it is better to use `calloc`
  14. * otherwise you will need to set `LL_NEXT` to `NULL`
  15. */
  16. if (!(item = calloc(1, sizeof(*item))))
  17. errx(!0, "failed to allocate memory");
  18. item->x = x;
  19. item->y = y;
  20. /*
  21. * if you not used calloc:
  22. * LL_NEXT(item) = NULL;
  23. */
  24. LL_APPEND(*list, item);
  25. }
  26. int
  27. cmp(node *item, int x)
  28. {
  29. return !(item->x == x);
  30. }
  31. int
  32. main(void)
  33. {
  34. node *list = NULL, *list2 = NULL;
  35. printf("size of node: %ld\n", sizeof(node));
  36. for (int i = 0; i < 10; i++)
  37. append(&list, i, ((float)i) * 14.88);
  38. node *i;
  39. LL_FOREACH(list, i) SHOW_NODE(i);
  40. size_t len;
  41. LL_LENGTH(list, len);
  42. printf("list len: %ld\n", len);
  43. puts("----------------------------------");
  44. LL_FOREACH(list, i) append(&list2, i->x, i->y);
  45. puts("reversed");
  46. LL_REVERSE(list);
  47. LL_FOREACH(list, i) SHOW_NODE(i);
  48. puts("----------------------------------");
  49. LL_CONCAT(list, list2);
  50. LL_LENGTH(list, len);
  51. printf("list len: %ld\n", len);
  52. LL_FOREACH(list, i) SHOW_NODE(i);
  53. puts("----------------------------------");
  54. printf("search x == 5: ");
  55. LL_SEARCH(list, cmp, 5, i);
  56. SHOW_NODE(i);
  57. printf("search x == 1488: ");
  58. LL_SEARCH(list, cmp, 1488, i);
  59. SHOW_NODE(i);
  60. puts("----------------------------------");
  61. LL_FOREACH(list, i)
  62. {
  63. printf("deleting ");
  64. SHOW_NODE(i);
  65. LL_DELETE(list, i);
  66. free(i);
  67. }
  68. return 0;
  69. }