C++ 堆的基本操作
- 格式:doc
- 大小:26.50 KB
- 文档页数:3
//堆的基本操作操作:初始化、插入、删除、清空
//经编译测试通过无任何问题!
文件Heap.h
typedef int ElemType;
struct Heap
{
ElemType *heap; //堆指针
int len;
int MaxSize;
};
#include
using namespace std;
void InitHeap(Heap& HBT) //初始化堆
{
HBT.MaxSize=10;
HBT.heap=new ElemType[HBT.MaxSize];
if(!HBT.heap)
{
cout<<"用于动态分配的内存空间用完,退出运行!"<
}
HBT.len=0;
}
void ClearHeap(Heap &HBT)
{
if(HBT.heap!=NULL)
{
delete [] HBT.heap;
HBT.heap=NULL;
HBT.len=0;
HBT.MaxSize=0;
}
}
bool EmptyHeap(Heap HBT)
{
return HBT.len==0;
}
void InsertHeap(Heap &HBT, ElemType item) //插入堆
{
if(HBT.len==HBT.MaxSize)
{
int k=sizeof(ElemType);
HBT.heap=(ElemType*)realloc(HBT.heap,2*HBT.MaxSize*k);
if(HBT.heap=NULL)
{
cout<<"动态可分配的存储空间用完,退出运行!"<
}
HBT.MaxSize=2*HBT.MaxSize;
}
int i=HBT.len;
while(i!=0)
{
int j=(i-1)/2;
if(item<=HBT.heap[j]) break;
HBT.heap[i]=HBT.heap[j];
i=j;
}
HBT.heap[i]=item;
HBT.len++;
}
ElemType DeleteHeap(Heap &HBT)
{
if(HBT.len==0)
{
cerr<<"堆为空,退出运行!"<
}
ElemType temp=HBT.heap[0];
HBT.len--;
if(HBT.len==0) return temp;
ElemType x=HBT.heap[HBT.len];
int i=0,j=1;
while(j<=HBT.len-1)
{
if(j
HBT.heap[i]=HBT.heap[j];
i=j;
j=2*i+1;
}
HBT.heap[i]=x;
return temp;
}
文件heap.cpp
#include
#include
#include"Heap.h"
#include
using namespace std;
int main()
{
int i=0,n,x;
Heap HBT;
InitHeap(HBT); //执行初始化操作
cout<<"输入堆的元素个数:";
cin>>n;
cout<<"输入堆:";
for(i=0;i
cin>>x;
InsertHeap(HBT,x); //插入堆
}
cout<<"输出所得的堆:"<
{
x=DeleteHeap(HBT); //删除堆
cout<
cout<<",";
}
cout<
}