求一个优先队列的C代码~
上网查过很多优先队列代码都是C++的~直接调用模板类的~~打算找一个用C实现的~实现函数部分是自己弄的
~~~打算放假有时间自己研习一下~~~
PS:如果不知道什么是优先队列可以上网搜搜~网上有详细的解释~
~~~
2017-07-03 19:28

2017-07-03 19:30

2017-07-03 19:37
2017-07-03 19:43
程序代码:#ifndef _BinHeap_H
struct HeapStruct;
typedef struct HeapStruct *PriorityQueue;
PriorityQueue
Initialize( int MaxElements );
void
Destroy( PriorityQueue H );
void
MakeEmpty( 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( MaxElements < MinPQSize )
Error( "Priority queue size is too samll" );//Error是报错函数,不需要知道它的具体功能,你只要知道它是干嘛的就行。
H = malloc( sizeof( struct HeapStruct ) );
if( NULL == H )
FatalError( "Out of space!!!" );
H->Elements = malloc( ( MaxElements + 1 ) * sizeof( ElementType ) );
if( NULL == H->Elements )
FatalError( " Out of space!!!" );
H->Capacity = MaxElements;
H->Size = 0[ 0 ] = MinData;//MinData是一个人为选择的标记,用来在Insert函数中跳出while循环,当然也还有别的方法,示例代码选择了一个比较简单的方法,以输入0-10的序列为例,那么MinData的值就该选择一个负数,例如-1
}
void
Insert( ElementType X, PriorityQueue H )
{
int i;
if( IsFull( H ) )
{
Error( "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 ) )
{
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;
}
[此贴子已经被作者于2017-7-3 20:21编辑过]

2017-07-03 20:18

2017-07-03 21:07
2017-07-03 21:18

2017-07-04 12:43
[此贴子已经被作者于2017-7-4 14:19编辑过]

2017-07-04 14:18

2017-07-04 14:30