c中的节点和结构

时间:2015-06-21 16:11:35

标签: c struct nodes huffman-code

我正在尝试制作一个霍夫曼编码器......但我遇到了一些问题...

这是我定义节点结构的方式..

struct node{

int type,prob;
char *code;
struct node *left, *right;

};

按概率排序,我创建了一个新节点

struct node join_nodes(struct node no1, struct node no2)
{
    struct node aux; 

    aux.type = 1; 
    aux.prob = no1.prob + no2.prob;
    aux.right = &no1; 
    aux.left = &no2;

    return aux;

}

然后我把这个新节点放在节点列表中..

   void sort_hufman(struct node order_list[], struct node list[])
{
        int i = N, len = N; 
        struct node aux;
        for(i=N; i>N-2;i--)
        {
                sort(order_list, i);
                len = len +1; 

                aux = join_nodes(order_list[i-1],order_list[i-2]);

                list[len-1] = order_list[i-2] = aux;

        }
}

问题在于,在这个函数中,我的第一个子节点类型是0和0,这意味着它们是叶子但是我知道它们在代码中变成了类型1和0 ...我认为这是因为(我不知道为什么子节点的指针指向同一个方向)..但它一定不能改变..

其中列表和订单列表我已经定义为* list并且我使用malloc在内存中节省了空间......

我不知道它发生了什么......

谁能帮助我?

3 个答案:

答案 0 :(得分:0)

您的代码至少存在两个问题:一个是严重的,一个是命名。

在功能

struct node join_nodes(struct node no1, struct node no2)

no1no2按值传递。出于所有实际目的,它们是临时物体。所以行

aux.right = &no1; 
aux.left = &no2;

有问题。你指向即将死亡的物体的指针。一旦该函数存在,您就不能指望它们中的任何内容。它们只是垃圾对象。

考虑按地址传递对象,而不是按值传递:

struct node join_nodes(struct node *no1, struct node *no2)
{
Tnode_pointer aux = (Tnode_pointer)malloc(sizeof(Tnode));

    aux->type = 1; 
    aux->prob = no1->prob + no2->prob;
    aux->right = no1; 
    aux->left = no2;

    return aux;
}

aux = join_nodes(order_list[i-1],order_list[i-2]);

struct node{
...
int ...prob;
};

这肯定不是概率。你的意思可能是基数。

答案 1 :(得分:0)

//I'm sorry I had to change the arguments to your function 

typedef struct node *Tnode_pointer;    
typedef struct node {
    int type,prob;
    char *code;
    Tnode_pointer left, right;
} Tnode;

Tnode_pointer join_nodes(Tnode *no1, Tnode *no2)
{
    Tnode_pointer aux = (Tnode_pointer)malloc(sizeof(Tnode));

    aux->type = 1; 
    aux->prob = no1->prob + no2->prob;
    aux->right = no1; 
    aux->left = no2;

    return aux;
}

答案 2 :(得分:-1)

typedef struct node *Tnode_pointer;    
typedef struct node {
    int type,prob;
    char *code;
    Tnode_pointer left, right;
} Tnode;

Tnode_pointer join_nodes(Tnode no1, Tnode no2)
{
    Tnode_pointer aux = (Tnode_pointer)malloc(sizeof(Tnode));

    aux->type = 1; 
    aux->prob = no1.prob + no2.prob;
    aux->right = &no1; 
    aux->left = &no2;

    return aux;
}