Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #include "pqueue.h"
00022 #include "helper.h"
00023
00029 PriorityQueue* pq_init( ) {
00030 PriorityQueue *pq=(PriorityQueue*)malloc(sizeof(PriorityQueue));
00031 pq->root=NULL;
00032 return pq;
00033 }
00034
00035 PQnode* pqnode_init( void *c, double priority ){
00036 PQnode *pq;
00037 pq = (PQnode*)malloc(sizeof(PQnode));
00038 pq->priority=priority;
00039 pq->content = c;
00040 pq->next = NULL;
00041 return pq;
00042 }
00043
00044 void pq_insert( PriorityQueue *pq, void *c, double prior ){
00045 PQnode *node=pqnode_init( c, prior );
00046 PQnode *it=pq->root;
00047
00048 dprintf("Inserting node %p with priority %f\n", c, prior );
00049 if( it==NULL || prior<it->priority ){
00050 node->next=pq->root;
00051 pq->root=node;
00052 return;
00053 }
00054
00055 while( 1 ){
00056 if( it->next==NULL ){
00057 it->next = node;
00058 return;
00059 } else if( prior<it->next->priority ){
00060 node->next = it->next;
00061 it->next = node;
00062 return;
00063 } else {
00064 it=it->next;
00065 }
00066 }
00067 }
00068
00074 PQnode* pq_pop_node( PriorityQueue *pq ){
00075 PQnode *tmp;
00076 if( pq->root==NULL ){
00077 warnprintf("Popping from empty PQ\n");
00078 return NULL;
00079 }
00080 tmp = pq->root;
00081 pq->root = tmp->next;
00082 tmp->next=NULL;
00083 return tmp;
00084 }
00085
00091 void* pq_pop( PriorityQueue *pq ){
00092 PQnode *tmp;
00093 void *content;
00094
00095 tmp = pq_pop_node( pq );
00096 content = tmp->content;
00097 pqnode_free( tmp );
00098
00099 return content;
00100 }
00101
00102
00103 void pq_print( FILE *out, PriorityQueue *pq ){
00104 fprintf( out, "PQ(%p)=[ ", pq );
00105 pqnode_print( out, pq->root );
00106 fprintf( out, " ]\n");
00107 }
00109 void pqnode_print( FILE *out, PQnode *N ){
00110 if( N==NULL ){
00111 return;
00112 }
00113 fprintf( out, "(%p,%.2f) ", N->content, N->priority );
00114 pqnode_print( out, N->next );
00115 }
00116
00117 void pqnode_free( PQnode *n ){
00118 if( !n ) return;
00119 if( n->next ){
00120 pqnode_free( n->next );
00121 }
00122 free( n );
00123 }
00126 void pq_free( PriorityQueue *pq ){
00127 pqnode_free( pq->root );
00128 free( pq );
00129 return;
00130 }