#include<stdio.h>
#include<stdlib.h>
#define MaxSize 101
#define T int
typedef struct minheap {
int Size;
T Elements[MaxSize];
}MinHeap;
typedef MinHeap PQueue;
//向下调整,针对位于上层的数值大的元素,按照完全二叉树下沉
void AdjustDown(T heap[], int r, int n);
//构建堆
void CreateHeap(MinHeap* hp);
//向上调整,针对位于底层的数值小的元素,按照完全二叉树上浮
void AdjustUp(T heap[], int n);
//优先权队列添加元素的函数
void Append(PQueue* pq, T x);
//判断是否为满
int IsFull(PQueue* pq);
//判断是否为空
int IsEmpty(PQueue* pq);
//优先权队列删除完全二叉树根元素的函数,也就是删除优先权队列最高有限权的元素,仅针对最小堆而言。
void Serve(PQueue* pq);
void main() {
int i;
PQueue* qq = (PQueue*)malloc(sizeof(PQueue));
qq->Size = 8;
//T array[MaxSize]= { 0, 61,28,81,43,36,47,83,5 };
qq->Elements[0] = 0;
qq->Elements[1] = 61;
qq->Elements[2] = 28;
qq->Elements[3] = 81;
qq->Elements[4] = 43;
qq->Elements[5] = 36;
qq->Elements[6] = 47;
qq->Elements[7] = 83;
qq->Elements[8] = 5;
CreateHeap(qq);
for (i = 1; i <= qq->Size; i++) {
printf("%d ", qq->Elements[i]);
}
Append(qq, 1);
printf("\n");
for (i = 1; i <= qq->Size; i++) {
printf("%d ", qq->Elements[i]);
}
printf("\n");
Serve(qq);
for (i = 1; i <= qq->Size; i++) {
printf("%d ", qq->Elements[i]);
}
printf("\n");
Serve(qq);
for (i = 1; i <= qq->Size; i++) {
printf("%d ", qq->Elements[i]);
}
printf("\n");
}
void CreateHeap(PQueue* hp) {
int i, n = hp->Size;
for (i = n / 2; i > 0; i--) {
AdjustDown(hp->Elements, i, n);
}
}
void AdjustDown(T heap[], int r, int n) {
int child = 2 * r;
T temp = heap[r];
while (child <= n)
{
if (child<n && heap[child]>heap[child + 1]) {
child++;
}
if (temp <= heap[child]) {
break;
}
heap[child / 2] = heap[child];
child *= 2;
}
heap[child / 2] = temp;
}
void AdjustUp(T heap[], int n) {
int i = n; T temp = heap[i];
while (i != 1 && temp < heap[i / 2]) {
heap[i] = heap[i / 2];
i /= 2;
}
heap[i] = temp;
}
int IsFull(PQueue* pq) {
if (pq->Size == MaxSize) {
return 1;
}
return 0;
}
int IsEmpty(PQueue* pq) {
if (pq->Size == 0) {
return 1;
}
return 0;
}
void Append(PQueue* pq, T x) {
if (IsFull(pq)) {
printf("优先权队列满了!\n");
}
else {
pq->Elements[++pq->Size] = x;
AdjustUp(pq->Elements, pq->Size);
}
}
void Serve(PQueue* pq) {
if (IsEmpty(pq)) {
printf("优先权队列空了!\n");
}
else {
pq->Elements[1] = pq->Elements[pq->Size--];
AdjustDown(pq->Elements, 1, pq->Size);
}
}
优先权队列------树-完全二叉树-最小堆-优先权队列
最新推荐文章于 2023-08-24 16:58:03 发布
本文介绍了如何使用C语言实现一个最小堆数据结构,构建PQueue(优先级队列),包括创建堆、向下调整、向上调整、添加元素(保持堆性质)、判断队列是否满和空,以及删除队列顶部元素。通过示例展示了优先级队列在实际操作中的应用。
摘要由CSDN通过智能技术生成