Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* modified by longoverdue */
- #include <stdint.h> // 15 line binary tree (0 = left node, 1 = right, 2 = key, 3 = value )
- #include <stdlib.h> // by graphitemaster 2016 (the same guy who did the 15 line hashtable)
- void **bnew(void) {
- return calloc(sizeof(void*[4]), 1);
- }
- void bdel(void **l) {
- if (l) bdel(l[0]), bdel(l[1]), free(l);
- }
- void ** bput(void **l, int k, int v) {
- return *(l += !!(k < (uintptr_t)l[2])) ?
- bput(*l, k, v) : (l = (void**) (*l = bnew()), l[2] = (void *)(uintptr_t)k, l[3] = (void *)(uintptr_t)v, l);
- }
- void **bget(void **l, int k) {
- return l ? (k < (uintptr_t) l[2]) ? bget(l[1], k) : (k == (uintptr_t) l[2]) ? l : bget(l[0], k) : 0;
- }
- // example of use
- #include <stdio.h>
- int main() {
- void **l = bnew(); // make new one (root is key = 0, value = 0)
- // add some things
- bput(l, 100, 100);
- bput(l, 200, 500);
- bput(l, 10, 35);
- bput(l, 75, 500);
- bput(l, 6000, 1337);
- void **a = bget(l, 75); // 500
- void **b = bget(l, 6000); // 1337
- printf("%d\n", (int)(uintptr_t) a[3]); // 3 is key, need to cast to int
- printf("%d\n", (int)(uintptr_t) b[3]);
- // something not in there
- void **c = bget(l, 42);
- printf("search for 42 should be null: %p\n", c);
- bdel(l);
- }
Advertisement
Add Comment
Please, Sign In to add comment