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