Insert an element into a min heap (No sentinel)———插入无哨兵的最小堆(PTA)

本文介绍了如何在C语言中实现一个最小堆的数据结构,包括`insertIntoHeap()`函数的填充,该函数用于在满载时插入新元素并保持堆的性质。
摘要由CSDN通过智能技术生成

题目描述:

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.

完整题解:


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

//堆是一种特殊的树(1,完全二叉树且每个节点都必须大于等于/小于等于其子树中每个节点的值)

/* 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){   // 初始化这个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) return 0;  
    //  returns 0 if heap is full. (There is NO fuction like the name "IsFull( )")
    int i;
    for(i=++h->size; i>1&& x<h->data[i/2]; i/=2)
        h->data[i] = h->data[i/2];
    h->data[i] = x;
    return 1;  // success
}
void printHeap(struct Heap* h) {
    printf("Heap elements:\n");
    for (int i = 1; i <= h->size; i++) {
        printf("%d ", h->data[i]);
    }
    printf("\n");
}
int main(){  /* main仅为示例,实际使用以上代码中两个函数的情况可能有所不同 */
    struct Heap *h;
    h = initHeap( 5 );
    insertIntoHeap(h,  1);
    insertIntoHeap(h,  10);
    insertIntoHeap(h,  3);
    insertIntoHeap(h,  4);
    insertIntoHeap(h,  5);
    printHeap(h);
    return 0;
}

经过实际运行后所填空能够正常运行。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值