2
0

test-avl.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include "avl.h"
  5. #include "avl-cmp.h"
  6. #include "utils.h"
  7. #define OUT(fmt, ...) do { \
  8. fprintf(stdout, "%s: " fmt, __func__, ## __VA_ARGS__); \
  9. } while (0);
  10. struct node {
  11. struct avl_node avl;
  12. };
  13. static void test_basics()
  14. {
  15. size_t i;
  16. struct avl_tree t;
  17. struct node *temp;
  18. struct node *elem;
  19. struct node *last;
  20. struct node *first;
  21. const char *vals[] = {
  22. "zero", "one", "two", "three", "four", "five", "six",
  23. "seven", "eight", "nine", "ten", "eleven", "twelve"
  24. };
  25. avl_init(&t, avl_strcmp, false, NULL);
  26. OUT("insert: ");
  27. for (i=0; i<ARRAY_SIZE(vals); i++) {
  28. struct node *n = malloc(sizeof(struct node));
  29. n->avl.key = vals[i];
  30. int r = avl_insert(&t, &n->avl);
  31. fprintf(stdout, "%d=%s ", r, (char *)n->avl.key);
  32. }
  33. fprintf(stdout, "\n");
  34. OUT("insert duplicate: ");
  35. for (i=0; i<ARRAY_SIZE(vals); i++) {
  36. struct node *n = malloc(sizeof(struct node));
  37. n->avl.key = vals[i];
  38. int r = avl_insert(&t, &n->avl);
  39. fprintf(stdout, "%d=%s ", r, (char *)n->avl.key);
  40. if (r)
  41. free(n);
  42. }
  43. fprintf(stdout, "\n");
  44. first = avl_first_element(&t, first, avl);
  45. last = avl_last_element(&t, last, avl);
  46. OUT("first=%s last=%s\n", (char*)first->avl.key, (char*)last->avl.key);
  47. OUT("for each element: ");
  48. avl_for_each_element(&t, elem, avl) {
  49. fprintf(stdout, "%s ", (char*)elem->avl.key);
  50. }
  51. fprintf(stdout, "\n");
  52. OUT("delete 'one' element\n");
  53. elem = avl_find_element(&t, "one", elem, avl);
  54. avl_delete(&t, &elem->avl);
  55. free(elem);
  56. OUT("for each element reverse: ");
  57. avl_for_each_element_reverse(&t, elem, avl) {
  58. fprintf(stdout, "%s ", (char*)elem->avl.key);
  59. }
  60. fprintf(stdout, "\n");
  61. OUT("delete all elements\n");
  62. avl_for_each_element_safe(&t, elem, avl, temp) {
  63. avl_delete(&t, &elem->avl);
  64. free(elem);
  65. }
  66. }
  67. int main()
  68. {
  69. test_basics();
  70. return 0;
  71. }