优先队列,数组赋不了值
程序代码:/*
*优先队列:大根堆
*/
#include<stdio.h>
#include<stdlib.h>
#define MAX_PQ_SIZE 100
#define element_type unsigned int
#define INI_MAX 0
typedef struct heap_struct
{
element_type max_heap_size;//堆中最大元素的个数
element_type size;//存放在堆中的实际元素的个数
element_type *elements;
}*PRIORITY_QUEUE;
PRIORITY_QUEUE create_pq(unsigned int max_elements)
{
PRIORITY_QUEUE H;
if(max_elements>MAX_PQ_SIZE)
printf("Priority queue size is too large!\n");
H=(PRIORITY_QUEUE)malloc(sizeof(struct heap_struct));
if(NULL==H)
printf("Out of space!\n");
/*Allocate the array+one extra for sentinel*/
H->elements=(element_type *)malloc((max_elements+1)*sizeof(element_type));
if(NULL==H->elements)
printf("Out of space!\n");
H->max_heap_size=max_elements;
H->size=0;
H->elements[0]=INI_MAX;//哨兵元素
return H;
}
bool isEmptyPriorityQueue(PRIORITY_QUEUE H)
{
return H->size==0;
}
/*H->element[0] is a sentinel*/
void insert(PRIORITY_QUEUE H,element_type x)
{
unsigned int i;
if(H->size==H->max_heap_size)
printf("Prinority queue if full!\n");
else
{
i=++H->size; /*the position of the new element*/
while(H->elements[i/2]<x)/*compare with the value of parent node*/
{
H->elements[i]=H->elements[i/2];/*swap down*/
i/=2;/*one level up*/
}
H->elements[i]=x;/*the finial position*/
}
}
element_type delete_max(PRIORITY_QUEUE H)
{
unsigned int i,child;
element_type max_element,last_element;
if(0==H->size)
{
printf("Priority queue is empty!\n");
return H->elements[0];
}
max_element=H->elements[1];/*first node is the*/
last_element=H->elements[H->size--];/*delete one node*/
for(i=1;i*2<=H->size;i=child)
{
/*find bigger child*/
child=i*2;
if((child!=H->size)&&(H->elements[child+1]>H->elements[child]))
child++;
if(last_element<H->elements[child])/*not yet the biggest*/
H->elements[i]=H->elements[child];/*child move up*/
else
break;/*is the biggest*/
}
H->elements[i]=last_element;/*set here*/
return max_element;
}
element_type topPriorityQueue(PRIORITY_QUEUE H)
{
if(isEmptyPriorityQueue(H))
{
printf("Priority queue is empty!\n");
return H->elements[0];
}
else
return H->elements[1];
}
void printPriorityQueue(PRIORITY_QUEUE H)
{
unsigned int i;
while(!isEmptyPriorityQueue(H))
{
for( i=0;i<H->size;i++)
printf("%d",H->elements[i]);
}
}
int main()
{
PRIORITY_QUEUE pq=NULL;
unsigned int max_elements;
printf("please input the number of max_elements:\n");
scanf("%d",&max_elements);
create_pq(max_elements);
while(max_elements)
{
pq->elements[max_elements]=max_elements--;
insert(pq,pq->elements[max_elements]);
}
printf("Priority queue initializtion finish!");
printPriorityQueue(pq);
printf("\n\n");
return 0;
}








