左スタックの実装
3554 ワード
ヘッダファイル:
具体的な実装:
作者のブログ:クリックしてリンクを開く
#ifndef LeftistHeap_H
#define LeftistHeap_H
#include
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);
else
return 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< *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<data;
}
作者のブログ:クリックしてリンクを開く