直接给出代码如下
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <memory.h> using namespace std; class minHeap { private: int maxSize;//heap中存放元素的最大数量 int index;//有效数据游标 int *heapArray; public: minHeap(int size); virtual ~minHeap(); int insert(int val); int pop(int *res); void printHeap(); }; void minHeap::printHeap() { int i = 0; cout<<"print mini heap:"<<endl; for(i=0; i<=this->index; i++) { cout<<this->heapArray[i]<<" "; } cout<<endl; return; } minHeap::minHeap(int size) { if(size <= 0) { this->heapArray = NULL; return; } this->heapArray = (int*)malloc(sizeof(int)*size); if(NULL == this->heapArray) { cout<<"malloc heap array failed"<<endl; } this->maxSize = size; this->index = -1; memset(this->heapArray, 0, sizeof(int)*size); } int minHeap::insert(int val) { int x = 0; int i = this->index; int j = 0; //堆已经放满了 //暂时不支持heap扩展 if(i >= this->maxSize -1) { return -1; } i++; while(i > 0) { j = (i-1)/2;//parent if(val >= this->heapArray[j]) { break; } this->heapArray[i] = this->heapArray[j]; i = j; } this->heapArray[i] = val; this->index++; return 0; } int minHeap::pop(int *res) { int val = 0; int i = 0; int j = 0; if(this->index < 0 || this->heapArray == NULL) { cout << "the heap is empty." <<endl; return -1; } //返回堆顶不元素 *res = this->heapArray[0]; //取最后一个元素 val = this->heapArray[this->index]; i = 0; j = 2*i+1; //从根节点开始调整 while(j <= this->index) { if(j<this->index && this->heapArray[j] > this->heapArray[j+1]) { j++; } if(val < this->heapArray[j]) { break; } this->heapArray[i] = this->heapArray[j]; i = j; j = 2*i+1; } this->heapArray[i] = val; this->index--; return 0; } minHeap::~minHeap() { free(this->heapArray); this->maxSize = 0; this->index = -1; } int main(int argc, char **argv) { minHeap *pHeap = new minHeap(10); int i = 0; int res = 0; for(i=0; i<10; i++) { pHeap->insert(10-i); } pHeap->printHeap(); cout<<"pop start"<<endl; pHeap->pop(&res); cout << res <<endl; pHeap->pop(&res); cout << res <<endl; pHeap->pop(&res); cout << res <<endl; cout<<"pop end"<<endl; pHeap->printHeap(); delete pHeap; return 0; }