左式堆合并的实现

左式堆合并的实现

源自废弃的 csdn blog

//define the leftist heap struct
typedef struct Leftist pLeftist;
struct Leftist{

    int element;
    pLeftist left, right;
    int npl;
};

//build the merged leftist heap and return it
pLeftist BuildHeap(LeftistQueue q){

    Leftist h1, h2;

    while(!IsEmpty(q)){
        h1 = Dequeue(q);
        if(IsEmpty(q))
            return h1;      //the leftist heap has been built
        h2 = Dequeue(q);

        Enqueue(q, Merge(h1, h2));  //enqueue the new merged leftist heap
    }

    return NULL;    //there is no leftist heap in queue
}

pLeftist Merge(Leftist h1, Leftist h2){

    if(!h1)
        return h2;
    if(!h2)
        return h1;  

    if(h1->element<h2->element)     //compare the element and choose the root
        return MergeHeap(h1, h2);
    else
        return MergeHeap(h2, h1);
}

pLeftist MergeHeap(Leftist h1, Leftist h2){

    if(!h1->left){
        h1->left = h2;      //single node
    }else{
        h1->right = Merge(h1->right, h2);
        if(h1->left->npl<h1->right->npl)    //make left child's npl >= right's
            SwapChl(h1);
        h1->npl = h1->right->npl+1;     //make the npl equalling its right child+1
    }

    return h1;  //return the root
}

分析

  • 左式堆而言,较于小根堆

    • 合并速度快,O(n)
    • 链表比数组带来更多的开销,并且多一个域(npl)
    • 代码相对复杂,其实也不复杂
  • 较于leftist heap,有个skew heap,每次合并都左右换一下,不需要(npl),如果数据是随机的,也是一个很不错的选择

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 序 2016年6月25日夜,帝都,天下着大雨,拖着行李箱和同学在校门口照了最后一张合照,搬离寝室打车去了提前租...
    RichardJieChen阅读 5,172评论 0 12
  • 1.把二元查找树转变成排序的双向链表 题目: 输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。 要求不...
    曲终人散Li阅读 3,371评论 0 19
  • 最近一段时间,油腻中年人这个词忽然就霸屏了。 先是有人贴出油腻中年男人的标志,男人不甘心,随后贴出油腻中年妇女的标...
    田安芸阅读 563评论 0 2
  • 001并不是学的什么专业,你就只能做和那个专业相关的工作。身边有很多朋友都做了和专业无关的工作,比如学医疗器械的做...
    921麻麻阅读 253评论 0 2
  • 活出生命的意义。 这本书的作者弗兰克尔,二战期间,美国领事馆通知他可以申领一个美国签证,他本可以逃出奥地利,不被抓...
    谭皓匀阅读 372评论 0 3