人生艰难,听来个谜语给大家讲讲,娱乐一下。
话说某同学整了以下C++代码,运行就崩溃。
问:为啥?
等级考试以后公布答案。
#include<iostream>
using namespace std;
struct heap{
private:
int *root;
int heapSize;
int maxSize;
void build_Heap(){
int n = (heapSize+1)/2 -1;
for(int i = n;i>=0;i--){
max_Heapify(i);
}
}
public:
heap(int *a,int size){
heap(20);
cout<<"hhh";
for(int i = 0;i<size;i++){
root[i] = a[i];
}
heapSize = size;
build_Heap();
}
heap(int maxSize){
root = new int [maxSize];
}
heap(){
root = new int [20];
}
void copyBuild(int *a,int size){
cout<<"hhh";
for(int i = 0;i<size;i++){
root[i] = a[i];
}
heapSize = size;
build_Heap();
}
void max_Heapify(int i){
int leftChild = i*2+1;
int rightChild = i*2+2;
int max = root[i];
int maxLoc = i;
if(leftChild<heapSize&&root[leftChild]>max){
max = root[leftChild];
maxLoc = leftChild;
}
if(rightChild<heapSize&&root[rightChild]>max){
max = root[rightChild];
maxLoc = rightChild;
}
if(maxLoc!=i){
root[maxLoc] = root[i];
root[i] = max;
max_Heapify(maxLoc);
}
}
int pop_top(){
if(0==heapSize){
cout<<"error!!! this is an empty heap\n";
return -9999999;
}
if(1==heapSize){
heapSize = heapSize-1;
return root[0];
}
else {
int max = root[0];
root[0] = root[--heapSize];
max_Heapify(0);
return max;
}
}
void output(){
for(int i = 0;i<heapSize;i++){
cout<<root[i]<<" ";
if((i+1)%10==0) cout<<endl;
}
cout<<endl;
}
};
int main(){
int *a = new int [20];
for(int i = 0;i<9;i++){
a[i] = i;
cout<<a[i]<<" ";
}
int ss = 9;
heap *p = new heap(a,9);
cout<<"build heap\n";
p->output();
cout<<"pop_top "<<p->pop_top()<<endl;
}
No comments:
Post a Comment