leftist (左偏堆,插入与弹出功能的实现)

来源:互联网 发布:织梦dedecms教程 编辑:程序博客网 时间:2024/05/01 12:56
 与堆相比没有那么强烈的关系和限制。不过想想,如果要扩展原始堆,比如扩展为链表存储的形式,好像也就只能走左偏堆的路子。

#include  <stdio.h>
#include  <stdlib.h>

#define  NIL   99999

typedef  struct   _leftist
{
  int  key;
  int  dis;
  struct _leftist  *left;
  struct  _leftist  *right;
}leftist;

leftist  *newstruct (  int  key);

leftist  *nilstruct ( )
{
  static   leftist  *obj=NULL;
  if  (!obj )
    {
      obj=newstruct ( NIL);
      obj->key=NIL;
      obj->dis=0;
    }
  else
    {
    }
  return  obj;
}

leftist  *newstruct (  int  key)
{
  leftist  *obj=(leftist *)calloc ( 1 ,sizeof  (leftist));
  obj->dis=0;
  obj->key=key;
  return  obj;
}

leftist  *leftist_adjust ( leftist  *left)
{
  leftist  *tmp;
  if(!left->left)
    {
    }
  else
    {
      if(left->left->dis>= left->right->dis)
 {
   left->dis=left->right->dis+1;
   return  left;
 }
    }

  tmp=left->left;
  left->left=left->right;
  left->right=tmp;

  if(!left->right)
    {
      left->dis=0;
    }
  else
    {
      left->dis=left->right->dis+1;
    }
  return  left;
}

leftist * leftist_merge ( leftist *left ,leftist  *right)
{
  if(!left)
    {
      return  right;
    }
  if (!right)
    {
      return  left;
    }
  if (left->key < right->key)
    {
      left->right=leftist_merge ( left->right ,right );
      return   leftist_adjust (left);

    }
  else
    {
      right->right=leftist_merge  ( left ,right->right);
      return  leftist_adjust ( right );
    }
}

leftist  *leftist_pop ( leftist  **head)
{
  leftist  *result=*head;
  *head=leftist_merge  (  result->left ,result->right );
  return  result;

int main()
{
  int  i;
  leftist  *head=NULL;
  leftist  *obj=NULL;
  int   a[]={11,45,32,22,145,333,789,76,31,90,10,20,50,666,1111,9};
  for(i=0;i<sizeof (a )/sizeof (int );i++)
    {
      obj=newstruct (  a[i]);
      head= leftist_merge ( head ,obj );
    }

  while(1)
    {
      if (! head->left  &&  !head->right )
 {
   obj=head;
   printf(" %d  ",obj->key);
   break;
 }
      obj=leftist_pop ( &head);
      printf(" %d  ",obj->key);
    }

}