libvieter/src/heap/vieter_heap.c

90 lines
1.8 KiB
C
Raw Normal View History

#include "vieter_heap.h"
#include "vieter_heap_tree.h"
#include <stdlib.h>
struct vieter_heap {
vieter_heap_tree *tree;
};
vieter_heap *vieter_heap_init() { return calloc(1, sizeof(vieter_heap)); }
2023-01-22 20:34:05 +01:00
uint64_t vieter_heap_size(vieter_heap *heap) {
uint64_t size = 0;
vieter_heap_tree *tree = heap->tree;
while (tree != NULL) {
2023-01-24 12:07:30 +01:00
size |= (uint64_t)1 << tree->order;
2023-01-22 20:34:05 +01:00
tree = tree->next;
}
return size;
}
2023-01-24 12:07:30 +01:00
void vieter_heap_free(vieter_heap *heap) {
vieter_heap_tree *tree = heap->tree;
vieter_heap_tree *next;
while (tree != NULL) {
next = tree->next;
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_node = vieter_heap_node_init();
new_node->key = key;
new_node->data = data;
2023-01-24 12:07:30 +01:00
vieter_heap_tree *new_tree = vieter_heap_tree_init(new_node, NULL, 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) {
2023-01-24 12:07:30 +01:00
if (heap->tree == NULL) {
return vieter_heap_empty;
}
if (heap->tree->order == 0) {
*out = heap->tree->root->data;
vieter_heap_tree_free(heap->tree);
heap->tree = NULL;
return vieter_heap_ok;
}
return vieter_heap_ok;
}
vieter_heap_error vieter_heap_peek(void **out, vieter_heap *heap) {
2023-01-22 20:34:05 +01:00
if (heap->tree == NULL) {
return vieter_heap_empty;
}
vieter_heap_tree *tree = heap->tree;
2023-01-24 12:07:30 +01:00
uint64_t smallest_key = tree->root->key;
*out = tree->root->data;
while (tree->next != NULL) {
tree = tree->next;
2023-01-22 20:34:05 +01:00
if (tree->root->key < smallest_key) {
smallest_key = tree->root->key;
*out = tree->root->data;
}
}
return vieter_heap_ok;
}