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

程序填空题:Insert an element into a min heap (No sentinel)

Luz4年前 (2021-05-10)题库1041
The program below contains a function `insertIntoHeap( )` which inserts an element into a min heap/priority queue(最小堆).

Fill in the blanks to complete the function.

(There is **NO** sentinel(哨兵) in heap)
```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 insertIntoHeap(struct Heap* h, int x){
if( @@[h->size == h->capacity](1) ) return 0; // returns 0 if heap is full. (There is NO fuction like the name "IsFull( )")
int i;
for(i=++h->size; @@[i>1](1) && @@[h->data[i/2]>x](2); @@[i/=2](1))
h->data[i] = @@[ h->data[i/2] ](2);
h->data[i] = @@[x](1) ;
return 1; // success
}
int main(){ /* main仅为示例,实际使用以上代码中两个函数的情况可能有所不同 */
struct Heap *h;
h = initHeap( 100 );
insertIntoHeap(h, 2018);
return 0;
}
```





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

第2空:i>1

第3空:h->data[i/2]>x

第4空:i/=2

第5空: h->data[i/2]

第6空:x

发表评论

访客

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