MOOC Zhejiang University Data Structure-05-Tree 7 Path in the Heap (25 puntos)

Consulte este artículo y la explicación de la inserción de heap en MOOC, y consulte este artículo 05-Tree 7 Path in the heap (25 puntos)
Error 1: ph-> element = (int *) malloc ((n + 1) * sizeof (int)); // Olvidé asignar espacio para el puntero

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

Error 2: // Necesito agregar un juicio aquí si la pila está llena
if (ph-> size == ph-> maxsize) {/
return;
}
Si está llena, no la inserte, inténtelo, usted puede pasar el
error sin juzgar 3: Recuerde el método para controlar el formato aquí

        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;
}

Supongo que te gusta

Origin blog.csdn.net/weixin_43919570/article/details/105229831
Recomendado
Clasificación