左式堆的实现

来源:互联网 发布:用python进行量化分析 编辑:程序博客网 时间:2024/04/30 21:27

头文件:

#ifndef LeftistHeap_H#define LeftistHeap_H#include<iostream>using namespace std;template< typename T >struct LeftistNode{T data;LeftistNode *left;LeftistNode *right;int npl;LeftistNode(const T & theData,LeftistNode* lt = NULL,LeftistNode * rt = NULL,int np = 0):data(theData),left(lt),right(rt),npl(np){}};template< typename T >class LeftistHeap{private:LeftistNode< T > *root;LeftistNode< T > * mergetree(LeftistNode< T > *h1,LeftistNode< T > *h2);LeftistNode< T > * merge(LeftistNode< T > *h1,LeftistNode< T > *h2);void swapChildren(LeftistNode< T > *t);void Free(LeftistNode< T > *p);public:LeftistHeap();LeftistHeap(const T args[],const int n);~LeftistHeap();bool isEmpty() const;T findMin() const;void Insert(const T &x);void deleteMin();void makeEmpty();void merge(LeftistHeap &rhs);};#endif

具体的实现:

#include "LeftistHeap.h"template< typename T >LeftistHeap< T > ::LeftistHeap(const T args[],const int n){int i;root = NULL;for(i = 0;i < n;++i){Insert(args[i]);}}template< typename T >LeftistHeap< T > ::~LeftistHeap(){Free(root);}template< typename T >void LeftistHeap< T >::merge(LeftistHeap & rhs){if(this == &rhs)//avoid aliasing problems{return;}root = merge(root,rhs.root);rhs.root = NULL;}/** * Internal method to merge two roots.*/template< typename T >LeftistNode< T > * LeftistHeap< T > ::merge(LeftistNode< T > *h1,LeftistNode< T > *h2){if(h1 == NULL)return h2;if(h2 == NULL)return h1;if(h1->data < h2->data)return mergetree(h1,h2);elsereturn mergetree(h2,h1);}/** * Internal method to merge two roots. * Assumes trees are not empty,and h1's root contains smallest item*/template< typename T > LeftistNode< T > * LeftistHeap< T > ::mergetree(LeftistNode< T > *h1,LeftistNode< T > *h2){if(h1->left == NULL)h1->left = h2;else{h1->right = merge(h1->right,h2);if(h1->left->npl < h1->right->npl)swapChildren(h1);h1->npl = h1->right->npl+1;}return h1;} /*** Insert x,duplicates allowed*/template < typename T >void LeftistHeap< T >::Insert(const T &x){root = merge(new LeftistNode< T >(x),root);}/*** Remove the minimum item.* Throws underflowException if empty*/template < typename T >void LeftistHeap< T > ::deleteMin(){if(isEmpty()){cerr<<"Error!The heap is empty!";exit(1);}LeftistNode<T> *oldRoot = root;root = merge(root->left,root->right);delete oldRoot;}template< typename T >bool LeftistHeap< T >::isEmpty() const{return root == NULL;}template< typename T>void LeftistHeap< T >::swapChildren(LeftistNode< T> *t){LeftistNode< T > *left = t->left;t->left = t->right;t->right = left;}template< typename T >void LeftistHeap< T >::makeEmpty(){Free(root);}template< typename T >void LeftistHeap< T >::Free(LeftistNode< T > *p){if(p == NULL)return;LeftistNode< T > *tmp = p;Free(p->left);Free(p->right);delete tmp; }template< typename T >T LeftistHeap< T >::findMin() const{if(isEmpty()){cerr<<"Error! The heap is empty!";exit(1);}return root->data;}

作者博客:点击打开链接