libvieter/src/heap/vieter_heap.c

84 lines
1.7 KiB
C

#include "vieter_heap.h"
#include "vieter_heap_tree.h"
#include <stdlib.h>
struct vieter_heap {
vieter_heap_node *tree;
};
vieter_heap *vieter_heap_init() { return calloc(1, sizeof(vieter_heap)); }
uint64_t vieter_heap_size(vieter_heap *heap) {
uint64_t size = 0;
vieter_heap_node *tree = heap->tree;
while (tree != NULL) {
size |= (uint64_t)1 << tree->order;
tree = tree->ptr.next_tree;
}
return size;
}
void vieter_heap_free(vieter_heap *heap) {
vieter_heap_node *tree = heap->tree;
vieter_heap_node *next;
while (tree != NULL) {
next = tree->ptr.next_tree;
vieter_heap_tree_free(tree);
tree = next;
}
free(heap);
}
vieter_heap_error vieter_heap_insert(vieter_heap *heap, uint64_t key,
void *data) {
vieter_heap_node *new_tree = vieter_heap_node_init();
new_tree->key = key;
new_tree->data = data;
new_tree->order = 0;
if (heap->tree == NULL) {
heap->tree = new_tree;
} else {
heap->tree = vieter_heap_tree_merge(heap->tree, new_tree);
}
return vieter_heap_ok;
}
vieter_heap_error vieter_heap_pop(void **out, vieter_heap *heap) {
if (heap->tree == NULL) {
return vieter_heap_empty;
}
heap->tree = vieter_heap_tree_pop(out, heap->tree);
return vieter_heap_ok;
}
vieter_heap_error vieter_heap_peek(void **out, vieter_heap *heap) {
if (heap->tree == NULL) {
return vieter_heap_empty;
}
vieter_heap_node *tree = heap->tree;
uint64_t smallest_key = tree->key;
*out = tree->data;
while (tree->ptr.next_tree != NULL) {
tree = tree->ptr.next_tree;
if (tree->key < smallest_key) {
smallest_key = tree->key;
*out = tree->data;
}
}
return vieter_heap_ok;
}