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

本文介绍了一种高效的数据结构——左偏堆,并通过代码详细展示了如何构建与调整左偏堆,以及如何进行元素的合并与弹出操作。左偏堆是一种自平衡的二叉查找树,特别适用于频繁合并的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 与堆相比没有那么强烈的关系和限制。不过想想,如果要扩展原始堆,比如扩展为链表存储的形式,好像也就只能走左偏堆的路子。

#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);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值