最大堆的操作

1、結構類型

typedef struct node
{
    int *p;  //實際上就是一個數組;
    int size;
    int max;
}NODE;

2、創建一個空堆

NODE *creat(int max)
{
    NODE *h=(NODE *)malloc(sizeof(NODE));
    h->p=(int *)malloc((max+1)*sizeof(int));
    h->size=0;
    h->max=max;
    h->p[0]=N;
    return h;
}

3、插入一個值,插入後依舊是一個最大堆;

void insert(NODE *h,int k)
{
    int i;
    if(IsFull(h))
    {
        printf("最大堆已滿\n");
        return ;
    }
    i=++h->size;
    while(h->p[i/2]<k)
    {
        h->p[i]=h->p[i/2];
        i=i/2;
    }
    h->p[i]=k;
}

4、刪除最大堆中的最大值;

int Hmax;
void deletemax(NODE *h)
{
    int parent,child;
    int temp;
    if(IsEmpty(h))
    {
        printf("最大堆已空\n");
        return ;
    }
    Hmax=h->p[1];
    temp=h->p[h->size];
    h->size--;
    int i=1;
    while(i*2<=h->size)
    {
        int son=i*2;
        if(son+1<=h->size&&h->p[son]<h->p[son+1])
        {
            son++;
        }
        if(temp<h->p[son])
        {
            h->p[i]=h->p[son];
        }
        else
        {
            break;
        }
        i=son;
    }
    h->p[i]=temp;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章