c语言实现二叉堆

生成二叉堆:

priorityqueue create(int max)
{
    priorityqueue h;
    h = (priorityqueue)malloc(sizeof(struct heap));
    h->data = (*int)malloc(sizeof(int)*(max+1));
    h->data[0] = INT_MIN;//很小的值
    h->size = 0;
    h->capacity = max;
    return h;

 } 

插入操作:

void insert(priorityqueue h,int data)
{
    //判断堆满没满
    if(h->size==h->capacity) 
    {
        printf("full!\n");
        return ;
    } 

    h->size++;
    int i;

    for(int i = h->size;h->data[i/2]>data;i/=2)
    {
        h->data[i] = h->data[i/2];

    }
    h->data[i] = data;
 }

删除操作:

int  deleted(priorityqueue h,int data)
{
    if(h->size==0) 
    {
        printf("failed\n");
        return 0 ;
    }

    int lastdata = h->data[h->size--];

    int mindata = h->data[1];

    int i,child;
    for(int i =1 ; i*2<=h->size ; i =child)
    {
        //找i节点左右子节点的最小值 
        child = 2*i;
        //存在右子节点 
        if(child!=h->size&&h->data[child]>h->data[2*i+1]){
            child++;
        } 
        if(lastdata > h->data[child])
        {
            h->data[i] =h->data[child];

        }

        else break;
    }

        h->data[i] = lastdata;

    return mindata;
} 

完整代码:

#include
#include
#include 

typedef struct heap* priorityqueue;

struct heap{
    int *data;
    int size;//目前堆中元素 
    int capacity;//堆中最大能放多少元素 
};



priorityqueue create(int max)
{
    priorityqueue h;
    h = (priorityqueue) malloc (sizeof(struct heap));
    h->data = (int*)malloc(sizeof(int)*(max+1));
    h->data[0] = INT_MIN;//很小的值
    h->size = 0;
    h->capacity = max;
    return h; 
}
void insert(priorityqueue h,int data)
{
    //判断堆满没满
    if(h->size==h->capacity) 
    {
        printf("full!\n");
        return ;
    } 

    h->size++;
    int i;

    for(int i = h->size;h->data[i/2]>data;i/=2)
    {
        h->data[i] = h->data[i/2];

    }
    h->data[i] = data;

} 


int  deleted(priorityqueue h,int data)
{
    if(h->size==0) 
    {
        printf("failed\n");
        return 0 ;
    }

    int lastdata = h->data[h->size--];

    int mindata = h->data[1];

    int i,child;
    for(int i =1 ; i*2<=h->size ; i =child)
    {
        //找i节点左右子节点的最小值 
        child = 2*i;
        //存在右子节点 
        if(child!=h->size&&h->data[child]>h->data[2*i+1]){
            child++;
        } 
        if(lastdata > h->data[child])
        {
            h->data[i] =h->data[child];

        }

        else break;
    }

        h->data[i] = lastdata;

    return mindata;
} 

int main()
{

}

你可能感兴趣的:(c语言实现二叉堆)