优先队列的简单实现

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define MAXSIZE 100
#define MinPQSize 1
typedef int ElementType;
struct HeadStruct{
	int Capacity;
	int Size;
	ElementType *Elements;
};
typedef struct HeadStruct *PriorityQueue;
//是否为空
int IsEmpty(PriorityQueue H)
{
	return H->Size == 0 ? 1 : 0;
}
//是否为满
int IsFull(PriorityQueue H)
{
	return H->Size == H->Capacity ? 1 : 0;
}
//初始化
PriorityQueue Initialize(int MaxElements)
{
	PriorityQueue H;
	if(MaxElements < MinPQSize)
	{
		printf("Priority queue is too small");
		exit(0);
	}
	H = (PriorityQueue)malloc(sizeof(struct HeadStruct));
	if(H == NULL)
	{
		printf("out of space");
		exit(0);
	}
	H->Elements = (ElementType*)malloc((MaxElements + 1) * sizeof(ElementType));
	if(H->Elements == NULL)
	{
		printf("out of space");
		exit(0);
	}
	H->Capacity = MaxElements;
	H->Size = 0;
	H->Elements[0] = 0;
	return H;
}
//删除
void Destroy(PriorityQueue H)
{
	free(H->Elements);
	free(H);
}
//清空
void MakeEmpty(PriorityQueue H)
{
	H->Size = 0;
}
//插入
void Insert(ElementType x, PriorityQueue H)
{
	int i;
	if(IsFull(H))
	{
		printf("priority queue is full");
		return;
	}
	for(i = ++H->Size; H->Elements[i/2] > x; i /= 2)
		H->Elements[i] = H->Elements[i/2];
	H->Elements[i] = x;
}
//删除
ElementType DeleteMin(PriorityQueue H)
{
	int i, Child;
	ElementType MinElement, LastElement;
	if(IsEmpty(H))
	{
		printf("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;
}
//寻找最小
ElementType FindMin(PriorityQueue H)
{
	return H->Elements[1];
}
//显示
void display(PriorityQueue H)
{
	for(int i = 1; i <= H->Size; i++)
		printf("%-5d", H->Elements[i]);
	printf("\n");
}
int main()
{	
	PriorityQueue H = Initialize(20);
	Insert(10, H);
	Insert(15, H);
	Insert(5, H);
	Insert(40, H);
	Insert(34, H);
	Insert(9, H);
	display(H);
	DeleteMin(H);
	display(H);
	DeleteMin(H);
	display(H);
	system("pause");
	return 0;
}

你可能感兴趣的:(优先队列的简单实现)