其中在union时时候故意加的wrap_head很有意义,另外打印阶段采用的是深度优先,还能打印合理的层数.
#include <stdio.h>
#include <stdlib.h>
#define NIL 9999
typedef struct _binheap
{
int key;
int degree;
struct _binheap *parent;
struct _binheap *sib;
struct _binheap *child;
}binheap;
binheap * newconstruct ( int key)
{
binheap *obj=(binheap*)calloc (1 ,sizeof (binheap));
obj->key=key;
return obj;
}
binheap * nilconstruct ()
{
static binheap *nilobj=NULL;
if(!nilobj)
{
nilobj=(binheap*)calloc (1 ,sizeof (binheap));
nilobj->key=NIL;
}
else
{
}
return nilobj;
}
binheap * binheap_merge ( binheap *left , binheap *right )
{
//funck sohu
if( !left )
{
return right;
}
if( !right)
{
return left;
}
if( left->degree < right->degree)
{
left->sib= binheap_merge ( left->sib , right);
return left;
}
else
{
right->sib= binheap_merge ( left , right->sib);
return right;
}
}
void re_link (binheap *left , binheap *right )
{
right->degree+=1;
left->sib=right->child;
right->child=left;
}
binheap * binheap_union ( binheap *left , binheap *right )
{
binheap *pre_x,*x,*next_x,*next_next_x;
binheap *wrap_head=nilconstruct ();
int label=0;
wrap_head->sib=binheap_merge(left,right);
pre_x=wrap_head;
while(1)
{
x=pre_x->sib;
if( !x)
{
break;
}
if(! x->sib)
{
pre_x=x; //for formallism
}
else
{
next_x=x->sib;
if( x->degree!=next_x->degree )
{
pre_x=x;
}
else
{
if ( ! next_x->sib)
{
if( x->key > next_x->key)
{
pre_x->sib=next_x;
re_link ( x ,next_x);
}
else
{
x->sib=next_x->sib;
re_link( next_x , x);
}
}
else
{
next_next_x=next_x->sib;
if( next_x->degree !=next_next_x->degree )
{
if( x->key > next_x->key)
{
pre_x->sib=next_x;
re_link ( x ,next_x);
}
else
{
x->sib=next_x->sib;
re_link( next_x , x);
}
}
else
{
pre_x=x;
}
}
}
}
}
return wrap_head->sib;
}
void insert ( int key ,binheap * * head)
{
binheap *newobj;
if(!*head)
{
*head=newconstruct(key);
}
else
{
newobj=newconstruct(key);
*head=binheap_union( newobj , *head);
}
}
void print(binheap *head,int level)
{
if(!head)
{
}
else
{
printf("level=%d key=%d \n",level,head->key);
print (head->child,level+1);
print(head->sib,level);
}
}
int main()
{
int i;
binheap *head=NULL;
int key[]={12,34,67,44,21,345,221,77,55,33};
for(i=0;i<sizeof (key) /sizeof (int) ;i++)
{
insert ( key[i] , &head);
}
print(head,0);
}