-->
当前位置:首页 > 题库 > 正文内容

程序填空题:Delete the minimum value from a min heap

Luz4年前 (2021-05-10)题库724
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.
```c
#include
#include
/* Definition of Heap struct */
struct Heap{
int *data; // 堆元素存储空间指针,堆元素按照二叉树顺序存储的方式,从data[1]开始存放,data[0]不使用,无哨兵元素
int capacity; // capacity(容量) of heap
int size; // number of heap elements
};
struct Heap* initHeap(int capacity){ // initialise the heap
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){ //将堆中最小元素的值放入pElement所指的变量,然后删除最小元素
if( @@[h->size == 0 ](1) ) return 0; // return 0 if heap is empty. (There is NO fuction like the name "IsEmpty( )")
@@[ *pElement ](1) = h->data[1];
int lastElement = @@[ h->data[h->size--] ](1);
int i, child;
for(i=1; i*2 <=h->size; i=child){
child = @@[ i*2 ](1);
if(child+1<=h->size && @@[ h->data[child]>h->data[child+1] ](2) )
child++;
if(lastElement > h->data[child])
@@[ h->data[i] = h->data[child] ](2);
else break;
}
h->data[i] = lastElement;
return 1;
}

int main(){ /* main仅为示例,实际使用以上代码中两个函数的情况可能有所不同 */
struct Heap *h;
h = initHeap( 100 );
/* the code for insert elements into heap is omitted */
int x, r;
r = deleteMin(h, &x); // function deleteMin() puts the minimum value of the heap into x
return 0;
}
```





答案:
第1空:h->size == 0

第2空: *pElement

第3空: h->data[h->size--]

第4空: i*2

第5空: h->data[child]>h->data[child+1]

第6空: h->data[i] = h->data[child]

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。