libevent2源码 min_heap

来源:互联网 发布:怎么添加打印机端口 编辑:程序博客网 时间:2024/06/06 02:51

位于 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;}



0 0
原创粉丝点击