Delete the minimum value from a min heap(从最小堆里删除最小值)PTA

The program below contains a function deleteMin( ) which get and removes the minimum value from a min heap/priority queue(最小堆) .

Fill in the blanks to complete the function.

解答代码如下:

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

/* 堆的定义 */
struct Heap{
    int *data;   // 堆元素存储空间指针,堆元素按照二叉树顺序存储的方式,从data[1]开始存放,data[0]不使用,无哨兵元素
    int capacity; // 堆的容量
    int size;  // 堆中元素的数量
};

/* 初始化堆 */
struct Heap* initHeap(int capacity){   
    struct Heap* h;
    h = (struct Heap*)malloc(sizeof(struct Heap));
    if(!h) return NULL;
    h->data = (int*)malloc(sizeof(int)*capacity+1);
    if(h->data == NULL){
        free(h);
        return NULL;
    }
    h->capacity = capacity;
    h->size = 0;
    return h;
};

/* 从堆中删除最小元素 */
int deleteMin(struct Heap* h, int* pElement){  
    if(h->size == 0) 
        return 0;  // 如果堆为空,则返回0

    *pElement = h->data[1];
    int lastElement = h->data[h->size--];
    int i, child;

    for(i = 1; i * 2 <= h->size; i = child){
        child = i * 2;
        if(child + 1 <= h->size && h->data[child + 1] < h->data[child])
            child++;

        if(lastElement > h->data[child])
            h->data[i] = h->data[child];
        else
            break;
    }

    h->data[i] = lastElement;
    return 1;
}

int main(){
    struct Heap *h;
    h = initHeap(100);
    /* 插入元素的代码被省略 */
    int x, r;
    r = deleteMin(h, &x); // deleteMin()函数将堆的最小值放入x中
    return 0;
}

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值