思路
采用数组实现
堆栈的实现采用了向上插入,和向下转移的方法,具体讲解请移步
https://www.cnblogs.com/zl0372/p/min_heap.html
实现
#include<iostream>
using namespace std;
#ifndef _HEAP_H
#define _HEAP_H
template<class T>
class Heap
{
private:
T *h;
int MaxSize;
int CurSize;
public:
Heap(int n){
h = new T[n];
CurSize=0;
MaxSize=n;
}
Heap(){
h = (T*)malloc(10*sizeof(T));
CurSize=0;
MaxSize=10;
}
void push(T e){
if(CurSize==MaxSize){
cout<<"over flow"<<endl;
return;
}
h[CurSize]=e;
CurSize++;
if(CurSize==MaxSize){
h = (T*)realloc(h,10*sizeof(T));
MaxSize+=10;
}
int currentIndex = CurSize-1;
while(currentIndex>0){
int parent = (currentIndex-1)/2;
if(e<h[parent]){
T temp = h[parent];
h[parent] = h[currentIndex];
h[currentIndex]=temp;
}else{
break;
}
currentIndex = parent;
}
}
T pop(){
if(CurSize==0){
cout<<"empty"<<endl;
}
int cur = 0;
T e = h[cur];
h[cur]=h[CurSize-1];
CurSize--;
while(cur<CurSize){
int left = cur*2+1;
int right =cur*2+2;
if(left>=CurSize){
break;
}
int maxIndex = left;
if(right<CurSize&&h[right]<h[maxIndex]){
maxIndex = right;
}
if(h[cur]>h[maxIndex]){
T temp = h[cur];
h[cur] = h[maxIndex];
h[maxIndex]=temp;
}else{
break;
}
cur = maxIndex;
}
return e;
}
bool empty(){
return CurSize==0;
}
~Heap(){
delete h;
}
};
#endif // _HEAP_H