Guest User

Untitled

a guest
Oct 5th, 2016
486
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. /* modified by longoverdue */
  2. #include <stdint.h> // 15 line binary tree (0 = left node, 1 = right, 2 = key, 3 = value )
  3. #include <stdlib.h> // by graphitemaster 2016 (the same guy who did the 15 line hashtable)
  4. void **bnew(void) {
  5. return calloc(sizeof(void*[4]), 1);
  6. }
  7. void bdel(void **l) {
  8. if (l) bdel(l[0]), bdel(l[1]), free(l);
  9. }
  10. void ** bput(void **l, int k, int v) {
  11. return *(l += !!(k < (uintptr_t)l[2])) ?
  12. bput(*l, k, v) : (l = (void**) (*l = bnew()), l[2] = (void *)(uintptr_t)k, l[3] = (void *)(uintptr_t)v, l);
  13. }
  14. void **bget(void **l, int k) {
  15. return l ? (k < (uintptr_t) l[2]) ? bget(l[1], k) : (k == (uintptr_t) l[2]) ? l : bget(l[0], k) : 0;
  16. }
  17.  
  18.  
  19. // example of use
  20. #include <stdio.h>
  21. int main() {
  22. void **l = bnew(); // make new one (root is key = 0, value = 0)
  23.  
  24. // add some things
  25. bput(l, 100, 100);
  26. bput(l, 200, 500);
  27. bput(l, 10, 35);
  28. bput(l, 75, 500);
  29. bput(l, 6000, 1337);
  30.  
  31. void **a = bget(l, 75); // 500
  32. void **b = bget(l, 6000); // 1337
  33. printf("%d\n", (int)(uintptr_t) a[3]); // 3 is key, need to cast to int
  34. printf("%d\n", (int)(uintptr_t) b[3]);
  35.  
  36. // something not in there
  37. void **c = bget(l, 42);
  38. printf("search for 42 should be null: %p\n", c);
  39.  
  40. bdel(l);
  41. }
Advertisement
Add Comment
Please, Sign In to add comment