c

时间:2019-12-13 22:49:43

标签: c heap element function-pointers adt

我正在尝试在c中实现maxheap的ADT。我在使用heapify函数时遇到麻烦。

这是我的h文件

typedef struct t_MaxHeap* MaxHeap;
typedef struct t_Node* Node;
typedef void *element;

typedef element (*copyFunc)(element);
typedef void (*PrintFunc)(element);
typedef void (*freeFunc)(element);
typedef element(*compareFunc)(element,element);
typedef element (*containFunc)(element);

这是我的结构(位于c文件中)

#include "MaxHeap.h"

struct t_Node
{
    element value;
};

struct  t_MaxHeap{
    int size;
    int capcity; //const
    char *name;
    copyFunc copyFunction;
    freeFunc freeFunction;
    PrintFunc printFunction;
    containFunc containFunction;
    compareFunc compareFunction;
    Node* array;
};

im创建堆没有问题..然后我定义了一个交换函数,将在heapify中使用..

void swap (MaxHeap new_MaxHeap,Node n1,Node n2 )
{
    Node temp= n1;
     n1=n2;
     n2=temp;
}

现在对于heapify函数,我对heapify函数有问题,我不确定如何解决它。

void heap_maxify(MaxHeap new_MaxHeap,element i)
{
    element largest=i;
    element a=new_MaxHeap->array[2*i];
    element b=new_MaxHeap->array[a+1];

    element b;
    b=a+1;
    if(a <=new_MaxHeap->size && new_MaxHeap->compareFunction(new_MaxHeap->array[largest],new_MaxHeap->array[a])==1)//1 means  a is bigger then largest
    {
        largest=a;
    }
    if(b <=new_MaxHeap->size && new_MaxHeap->compareFunction(new_MaxHeap->array[largest],new_MaxHeap->array[b])==1) //1 means b is bigger then largest
        {
            largest=b;
        }

    if (largest !=i){
        swap(new_MaxHeap,i,largest);
    }

}

我认为我的两个if语句都很好。问题在于将a设置为索引2i中的元素 和b,它位于当前元素

的索引2i + 1中

0 个答案:

没有答案