bst.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #ifndef BST_H
  2. #define BST_H
  3. #define bst_declare(name, type, idx_type) struct { \
  4. struct { \
  5. idx_type idx; \
  6. type elem; \
  7. void *left; \
  8. void *right; \
  9. } *head; \
  10. } name
  11. #define bst_init(name) do { \
  12. (name).head = NULL; \
  13. } while (0)
  14. #define bst_node_type(name) typeof(*((name).head))
  15. #define bst_insert(name, _elem, _idx) do { \
  16. bst_node_type(name) **cur = NULL; \
  17. \
  18. for (cur = &((name).head); ;) { \
  19. assert(cur != NULL); \
  20. \
  21. if (*cur == NULL) { \
  22. (*cur) = malloc(sizeof(bst_node_type(name))); \
  23. assert(*cur != NULL); \
  24. (*cur)->idx = _idx; \
  25. (*cur)->elem = _elem; \
  26. (*cur)->left = NULL; \
  27. (*cur)->right = NULL; \
  28. break; \
  29. } else { \
  30. assert((*cur)->idx != _idx); \
  31. \
  32. if (_idx < (*cur)->idx) { \
  33. cur = (bst_node_type(name) **)&((*cur)->left); \
  34. } else { \
  35. cur = (bst_node_type(name) **)&((*cur)->right); \
  36. } \
  37. } \
  38. } \
  39. } while (0)
  40. #define bst_find(name, _idx, _elemp) do { \
  41. bst_node_type(name) *cur = NULL; \
  42. \
  43. assert((_elemp) != NULL); \
  44. \
  45. for (cur = (name).head; cur != NULL; ) { \
  46. if (cur->idx == _idx) { \
  47. break; \
  48. } \
  49. \
  50. if (_idx < cur->idx) { \
  51. cur = (bst_node_type(name) *)(cur->left); \
  52. } else { \
  53. cur = (bst_node_type(name) *)(cur->right); \
  54. } \
  55. } \
  56. \
  57. if (cur != NULL) { \
  58. *(_elemp) = ((cur)->elem); \
  59. } else { \
  60. *(_elemp) = NULL; \
  61. } \
  62. } while (0);
  63. #if 0
  64. else { \
  65. cur = &((bst_node_type(name)((*cur)->right))); \
  66. } \
  67. (*cur).elem = elem; \
  68. (*cur).idx = idx; \
  69. }
  70. #endif
  71. #endif /* BST_H */