C语言优先队列作用,优先队列--C语言实现

优先队列--C语言实现

向乔布斯致敬

世界的今天因他而改变!

世界的今天因他而多彩!

JOBS

优先队列--C语言实现

/* binomial.h */

#ifndef _BINOMIAL_H_

#define _BINOMIAL_H_

typedef long element_type;

#define INFINITY (30000L)

#define MAX_TREES (14)

#define CAPACITY (16383)

struct bin_node;

typedef struct bin_node *bin_tree;

struct collection;

typedef struct collection *bin_queue;

#endif

/* end */

/**********************************************************************************************************/

/* binomial.c

* 实现了优先队列插入、合并、删除最小单元等操作

* nizqsut@http://doc.xuehai.net

*/

#include

#include

#include "binomial.h"

#include "fatal.h"

typedef struct bin_node *pos;

struct bin_node

{

element_type element;

pos left_child;

pos next_sibling;

};

struct collection

{

int cur_size;

bin_tree trees[ MAX_TREES ];

};

/*

合并两个优先队列,通过后h1返回新的优先队列指针

*/

static bin_queue

bq_merge( bin_queue h1, bin_queue h2 );

static int

is_empty( bin_queue h )

{

return h->cur_size == 0;

}

static int

is_full( bin_queue h )

{

return h->cur_size == CAPACITY;

}

/*

初始化一个空优先队列

返回空优先队列的指针

*/

static bin_queue

initialize( void )

{

bin_queue h;

int i;

h = malloc( sizeof( struct collection ) );

if ( h == NULL )

Error("Out of space!");

h->cur_size = 0;

for ( i = 0; i < MAX_TREES; i++ ){

h->trees[ i ] = NULL;

}

return h;

}

/* 删除一颗二项树 */

static void

destroy_tree( bin_tree t )

{

if ( t != NULL ){

destroy_tree( t->left_child );

destroy_tree( t->next_sibling );

free( t );

}

}

/*

static void

destroy_bq( bin_queue h )

{

int i;

for ( i = 0; i < MAX_TREES; i++ ){

destroy_tree( h->trees[ i ] );

h->trees[ i ] = NULL;

}

}

*/

/*

清除优先队列中所有的节点

*/

static bin_queue

make_empty( bin_queue h )

{

int i;

/*destroy_bq( h );*/

for ( i = 0; i < MAX_TREES; i++ ){

destroy_tree( h->trees[ i ] );

h->trees[ i ] = NULL;

}

h->cur_size = 0;

return h;

}

/*

插入一个节点

*/

static bin_queue

insert( element_type item, bin_queue h )

{

bin_tree new_node;

bin_queue bq_one_item;

new_node = malloc( sizeof( struct bin_node ) );

if ( new_node == NULL )

Error("Out of space!");

new_node->left_child = new_node->next_sibling = NULL;

new_node->element = item;

/* 先构造一个新优先队列放置新节点,然后与原来的优先队列合并 */

bq_one_item = initialize( );

bq_one_item->cur_size = 1;

bq_one_item->trees[ 0 ] = new_no

de;

return bq_merge( h, bq_one_item );

}

/*

删除优先队列中最小值的节点

*/

static element_type

delete_min( bin_queue h )

{

int i, j;

int min_tre

你可能感兴趣的:(C语言优先队列作用)