慕课浙大数据结构-05-树7 堆中的路径 (25分)

参考这篇文章,以及慕课中堆插入的讲解,并参考这篇文章05-树7 堆中的路径 (25分)
错误1: ph->element = (int*)malloc((n+1)*sizeof(int));//忘记给指针分配空间了

    ph->element = (int*)malloc((n+1)*sizeof(int));//忘记给指针分配空间了
    ph->element[0] = -10005;

错误2: //这里需要加一个判断堆满了么
if(ph->size==ph->maxsize){/
return;
}
如果满了就不插入,试了一下,不加判断也可以通过
错误3:这里控制格式的方法记住

        if(i==1){
    
    
            cout<<ph->element[1]<<endl;
        }
        else{
    
    
            cout<<ph->element[i]<<" ";
        }
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct heap *Pheap;
struct heap{
    
    
    int *element;
    int size;
    int maxsize;
};
Pheap create(int n);
Pheap create(int n){
    
    
    Pheap ph;
    ph = (Pheap)malloc(sizeof(struct heap));
    ph->element = (int*)malloc((n+1)*sizeof(int));//忘记给数组分配空间了
    ph->element[0] = -10005;
    ph->size = 0;//错写成1
    ph->maxsize = n;
    return ph;
}
void insert(Pheap ph, int t);
void insert(Pheap ph, int t){
    
    
    //这里需要加一个判断堆满了么
    if(ph->size==ph->maxsize){
    
    
        return;
    }
    int i;
    i = ++ph->size;//这个地方错写成 ph->size+1,疑问 函数也可以修改这个值了么,是因为用指针访问的么
    ph->element[i] = t;
    for(;t<ph->element[i/2];i = i/2){
    
    //wrong used ph->element[i]>ph->element[i/2]
        ph->element[i] = ph->element[i/2];//wrong used ph->element[i/2] = ph->element[i]; always make mistakes
    }
    ph->element[i] = t;
    //无返回值就可以return ph;
}
void print(Pheap ph,int m){
    
    
    for(int i=m;i>=1;i/=2){
    
    //竟然写成了i=0为条件,错的离谱
        if(i==1){
    
    
            cout<<ph->element[1]<<endl;
        }
        else{
    
    
            cout<<ph->element[i]<<" ";
        }
    }
}
int main(){
    
    
    int N,M;
    cin>>N>>M;
    Pheap ph;
    ph = create(N);
    for(int i=0;i<N;++i){
    
    
        int v;
        cin>>v;
        insert(ph,v);
    }
    for(int i=0;i<M;++i){
    
    
        int m;
        cin>>m;
        print(ph,m);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43919570/article/details/105229831
今日推荐