位于 minheap-internal.h , 是一个堆的实现
主要代码为:
堆的定义:
typedef struct min_heap
{
//堆各节点空间
struct event** p;
//n为节点数量,a为容量
unsigned n, a;
} min_heap_t;
插入新节点
int min_heap_push(min_heap_t* s, struct event* e)
{
//申请空间
if (min_heap_reserve(s, s->n + 1))
return -1;
//移动到正确位置
min_heap_shift_up_(s, s->n++, e);
return 0;
}
void min_heap_shift_up_(min_heap_t* s, unsigned hole_index, struct event* e)
{
unsigned parent = (hole_index - 1) / 2;
//父节点大于hole_index处节点
while (hole_index && min_heap_elem_greater(s->p[parent], e))
{
//父节点移到hole_index处
(s->p[hole_index] = s->p[parent])->ev_timeout_pos.min_heap_idx = hole_index;
//继续向上级节点寻找
hole_index = parent;
parent = (hole_index - 1) / 2;
}
//放入e
(s->p[hole_index] = e)->ev_timeout_pos.min_heap_idx = hole_index;
}
删除最小值
void min_heap_shift_down_(min_heap_t* s, unsigned hole_index, struct event* e)
{
unsigned min_child = 2 * (hole_index + 1);
while (min_child <= s->n)
{
//选择最小的子节点
min_child -= min_child == s->n || min_heap_elem_greater(s->p[min_child], s->p[min_child - 1]);
//父节点已经最小则无需继续
if (!(min_heap_elem_greater(e, s->p[min_child])))
break;
//从子节点继续向下
(s->p[hole_index] = s->p[min_child])->ev_timeout_pos.min_heap_idx = hole_index;
hole_index = min_child;
min_child = 2 * (hole_index + 1);
}
(s->p[hole_index] = e)->ev_timeout_pos.min_heap_idx = hole_index;
}