《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.1 KiB

12 years ago
  1. #ifndef __LIBS_SKEW_HEAP_H__
  2. #define __LIBS_SKEW_HEAP_H__
  3. struct skew_heap_entry {
  4. struct skew_heap_entry *parent, *left, *right;
  5. };
  6. typedef struct skew_heap_entry skew_heap_entry_t;
  7. typedef int(*compare_f)(void *a, void *b);
  8. static inline void skew_heap_init(skew_heap_entry_t *a) __attribute__((always_inline));
  9. static inline skew_heap_entry_t *skew_heap_merge(
  10. skew_heap_entry_t *a, skew_heap_entry_t *b,
  11. compare_f comp);
  12. static inline skew_heap_entry_t *skew_heap_insert(
  13. skew_heap_entry_t *a, skew_heap_entry_t *b,
  14. compare_f comp) __attribute__((always_inline));
  15. static inline skew_heap_entry_t *skew_heap_remove(
  16. skew_heap_entry_t *a, skew_heap_entry_t *b,
  17. compare_f comp) __attribute__((always_inline));
  18. static inline void
  19. skew_heap_init(skew_heap_entry_t *a)
  20. {
  21. a->left = a->right = a->parent = NULL;
  22. }
  23. static inline skew_heap_entry_t *
  24. skew_heap_merge(skew_heap_entry_t *a, skew_heap_entry_t *b,
  25. compare_f comp)
  26. {
  27. if (a == NULL) return b;
  28. else if (b == NULL) return a;
  29. skew_heap_entry_t *l, *r;
  30. if (comp(a, b) == -1)
  31. {
  32. r = a->left;
  33. l = skew_heap_merge(a->right, b, comp);
  34. a->left = l;
  35. a->right = r;
  36. if (l) l->parent = a;
  37. return a;
  38. }
  39. else
  40. {
  41. r = b->left;
  42. l = skew_heap_merge(a, b->right, comp);
  43. b->left = l;
  44. b->right = r;
  45. if (l) l->parent = b;
  46. return b;
  47. }
  48. }
  49. static inline skew_heap_entry_t *
  50. skew_heap_insert(skew_heap_entry_t *a, skew_heap_entry_t *b,
  51. compare_f comp)
  52. {
  53. skew_heap_init(b);
  54. return skew_heap_merge(a, b, comp);
  55. }
  56. static inline skew_heap_entry_t *
  57. skew_heap_remove(skew_heap_entry_t *a, skew_heap_entry_t *b,
  58. compare_f comp)
  59. {
  60. skew_heap_entry_t *p = b->parent;
  61. skew_heap_entry_t *rep = skew_heap_merge(b->left, b->right, comp);
  62. if (rep) rep->parent = p;
  63. if (p)
  64. {
  65. if (p->left == b)
  66. p->left = rep;
  67. else p->right = rep;
  68. return a;
  69. }
  70. else return rep;
  71. }
  72. #endif /* !__LIBS_SKEW_HEAP_H__ */