数据结构C语言描述 第六章 优先队列 堆

#pragma once

#include <iostream>


struct HeapStruct;
typedef struct HeapStruct* PriorityQueue;
PriorityQueue Initialize(int MaxElements);
void Destroy(PriorityQueue h);
void MakeEmpty(PriorityQueue h);
void Insert(int x, PriorityQueue h);
int DeleteMin(PriorityQueue h);
int Findmin(PriorityQueue h);
int IsEmpty(PriorityQueue h);
int IsFull(PriorityQueue h);

struct HeapStruct {
    int Capacity;
    int Size;
    int* Elements;
};
#include "Myheap.h"

PriorityQueue Initialize(int MaxElements)
{
    PriorityQueue H = new HeapStruct;
    H->Elements = new int[MaxElements];
    H->Size = 0;
    for (int i = 0; i < MaxElements; i++)
    {
        H->Elements[i] = -1;
    }
    H->Capacity = NULL;
    return H;
}

void Destroy(PriorityQueue h)
{
}


void MakeEmpty(PriorityQueue h)
{

}

void Insert(int x, PriorityQueue h)
{
    int i = ++h->Size;
    if (IsEmpty(h))
    {
        --h->Size;
        return;
    }
    
    while (true)
    {
        if (h->Elements[i / 2 - 1] != -1 && h->Elements[i/2-1] > x) {
            h->Elements[i] = h->Elements[i / 2 - 1];
            i = i / 2 - 1;
        }
        else
        {
            h->Elements[i] = x;
            break;
        }
    }
}

int DeleteMin(PriorityQueue h) {
    if (h->Size == 0) {
        
        return -1;
    }

    int minElement = h->Elements[1];
    int lastElement = h->Elements[h->Size--];
    int i = 1, child;

    // Percolate down
    for (; i * 2 <= h->Size; i = child) {
        child = i * 2;
        // Select the smaller child
        if (child != h->Size && h->Elements[child + 1] < h->Elements[child]) {
            child++;
        }
        // Check if the last element can be placed here
        if (lastElement > h->Elements[child]) {
            h->Elements[i] = h->Elements[child];
        } else {
            break;
        }
    }
    h->Elements[i] = lastElement;
    return minElement;
}


int Findmin(PriorityQueue h)
{
    return 0;
}

int IsEmpty(PriorityQueue h)
{
    return h->Size == 0;
}

int IsFull(PriorityQueue h)
{
    return 0;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值