优先队列的实现

本文介绍了优先队列的数据结构实现及其核心操作方法,包括初始化、插入元素、删除最小元素等,并提供了具体的C语言代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

优先队列的声明

#ifmdef _BinHeap_H

struct HeapStruct;
typedef struct HeapStruct *PriorityQueue;

PriorityQueue Initialize(int MaxElement);
void Destory(PriorityQueue H);
void MakwEmpty(PriorityQueue H)
void Insert(ElementType X,PriorityQueue H);
ElementType DeleteMin(PriorityQueue H);
ElementType FindMin(PriorityQueue H);
int IsEmpty(PriorityQueue H);
int IsFull(PriorityQueue H);

#endif

struct HeapStruct
{
    int Capacity;
    int Size;
    ElementType *Elements;
}

优先队列的初始化

PriorityQueue Initialize(int MaxElements)
{
    PriorityQueue H;
    if(MaxElement < MinPQSize)
        Error("Priority queue size is too small");
    H = malloc(sizeof(struct HeapStruct));
    if(H == NULL)
        FatalError("Out of space!!!");
    H->Elements = malloc((MaxElements + 1)*sizeof(ElementType));
    if(H->Elements == NULL)
        FatalError("Out of space!!!");
    H->Capacity = MaxElements;
    H->Size = 0;
    H->Elements[0] = MinData;
    
    return H;
}

插入一个元素到二叉树中

void Insert(ElementType X,PriorityQueue H)
{
    int i;
    if(IsFull(H))
    {
        Error("Priority queue is full");
        return 0;
    }
    for(i = ++H->Size;H->Elements[i/2] > X;i /= 2)
        H->Elements[i] = H->Elements[i/2];
    H->Elements[i] = X;
}

在二叉树中执行DeleteMin函数

ElementType DeleteMin(PriorityQueue H)
{
    int i,Child;
    ElementType MinElement,LastElement;
    
    if(IsEmpty(H))
    {
        Error("Priority queue is empty");
        return H->Elements[0];
    }
    MinElement = H->Elements[1];
    LastElement = H->Elements[H->Size--];
    for(i = 1;i*2 <= H->Size;i = Child)
    {
        Child = i*2;
        if(Child != H->Size && H->Elements[Child + 1] < H->Elements[Child])
            Child ++;
        if(LastElement > H->Elements[Child])
            H->Elements[i] = H->Elements[Child];
        else
            break;
    }
    H->Elements[i] = LastElement;
    return MinElement;
}

转载于:https://www.cnblogs.com/y3w3l/p/6369628.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值