二叉堆


#include <stdio.h>
#include <stdlib.h>

/**
* 经常使用 heap 实现 优先级队列
*/

#define MAX_SIZE 100

#define True 1
#define False 0
typedef short Boolean;
typedef struct node* pNode;
struct node{
int data;
};

pNode heap[MAX_SIZE+1]; /// index of first element is 1
int size;
Boolean isFull();
Boolean isEmpty();
void insert(pNode);
pNode delete(); / delete the biggest node
void print();
pNode getMax();



#include "deap.h"

void print()
{
if(isEmpty()){
return;
}

int i = 1;
while(i <= size){
printf("%d ", heap[i++]->data);
}
printf("\n");
}

Boolean isFull()
{
if(size == MAX_SIZE+1) return True;
return False;
}

Boolean isEmpty()
{
if(size == 0) {
printf("Empty deap\n");
return True;
}
return False;
}

// while 循环从最大堆的 新叶子结点 开始,
// 沿着到根结点的路径,直到根结点
// 使其父结点 i/2 的值 不小于 要插入的值
void insert(pNode elem)
{

if(isFull(size)){
printf("sizeo space\n");
return;
}

int i = ++size;
while(i!=1 && elem->data > heap[i/2]->data){ /// 把父结点移动到其子结点位置
heap[i] = heap[i/2];
i /= 2;
}

heap[i] = elem;
}

/// 删除根元素,然后把最后一个元素设为根元素,
/// 接着进行调整,使之复合最大堆/最小堆
pNode delete(){
pNode res = 0;
if(isEmpty()){
return 0;
}

res = heap[1]; /// 得到最大元素

pNode last = heap[size--]; /// 得到最后一个元素

//heap[1] = last;

int parent = 1; 从新的 根元素 开始
int child = 2; /// 新的根元素的 孩子

while(child <= size){
if(child < size && heap[child]->data < heap[child+1]->data){ // 比较兄弟结点,取较大者的下标
child++;
}
if(heap[child]->data > last->data){ 如果 较大的子结点 大于 新的 根结点
heap[parent] = heap[child]; 那么把 该子结点 移动到 父结点位置
parent = child; /// 当前子结点设为 起点 重新开始移动
child *= 2;
}else{
break;
}
}

heap[parent] = last;
return res;
}

pNode getMax(){
if(!isEmpty()){
return heap[1];
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值