HeadMain.h
#include<iostream>
using namespace std;
#include"Heap.h"
Heap.h
typedef int Elemtype;
class CHeap
{
public:
Elemtype *m_heap;
int m_len;
int m_MaxSize;
CHeap();
~CHeap();
void InitHeap(CHeap &HBT);
void ClearHeap(CHeap &HBT);
bool IsEmpty( CHeap &HBT);
void InsertHeap( CHeap & HBT, Elemtype item);
Elemtype DeleteHeap(CHeap &HBT);
};
Heap.cpp
#include"HeadMain.h"
CHeap::CHeap()
{
}
CHeap::~CHeap()
{
}
void CHeap::InitHeap(CHeap &HBT)
{
HBT.m_MaxSize=10;
HBT.m_heap = new Elemtype[HBT.m_MaxSize];
if(!HBT.m_heap)
{
cout<<"动态分配失败,退出程序"<<endl;
exit(1);
}
HBT.m_len=0;
}
void CHeap::ClearHeap(CHeap &HBT)
{
if(HBT.m_heap!=NULL)
{
delete[] HBT.m_heap;
HBT.m_heap=NULL;
HBT.m_len=0;
HBT.m_MaxSize=0;
}
}
bool CHeap::IsEmpty( CHeap &HBT)
{
return (bool)HBT.m_len;
}
void CHeap::InsertHeap( CHeap & HBT, Elemtype item)
{
if(HBT.m_len==HBT.m_MaxSize)
{
int k=sizeof(Elemtype);
HBT.m_heap=(Elemtype*)realloc(HBT.m_heap,2*HBT.m_MaxSize*k);
if(HBT.m_heap==NULL)
{
cout<<"动态分配失败,退出程序"<<endl;
exit(1);
}
HBT.m_MaxSize=2*HBT.m_MaxSize;
}
int i=HBT.m_len;
while(i!=0)
{
int j=(i-1)/2;
if(item>=HBT.m_heap[j])break;
HBT.m_heap[i]=HBT.m_heap[j];
i=j;
}
HBT.m_heap[i]=item;
HBT.m_len++;
}
Elemtype CHeap::DeleteHeap(CHeap &HBT)
{
if(HBT.m_len==0)
{
cout<<"堆为空,退出程序"<<endl;
exit(1);
}
Elemtype temp=HBT.m_heap[0];
HBT.m_len--;
if(HBT.m_len==0)return temp;
Elemtype x=HBT.m_heap[HBT.m_len];
int i=0;
int j=0;
while(j<=HBT.m_len-1)
{
if(j<HBT.m_len-1 && HBT.m_heap[j]>HBT.m_heap[j+1])
j++;
if(x<=HBT.m_heap[j]) break;
HBT.m_heap[i]=HBT.m_heap[j];
i=j;
j=2*i+1;
}
HBT.m_heap[i]=x;
return temp;
}
main.cpp
#include"HeadMain.h"
void main()
{
CHeap h;
//CHeap *heap = new CHeap();
h.InitHeap(h);
int a[10]={23,45,12,34,76,90,88,55,9,11};
for(int i=0;i<10;i++)
h.InsertHeap(h,a[i]);
while(h.IsEmpty(h))
{
cout<<h.DeleteHeap(h)<<endl;
}
}