c中的N元树

问题描述 投票:0回答:1

我正在尝试在C语言中实现一棵N元树。我知道如何确定要早生多少孩子的实现。但是我的问题是,我想使其具有动态性(我想调整子项的大小和子项的大小)

struct node    
{
    char * type;
    struct node **child;
    int children;
    int id;    
};

这是我的结构,我想使用指针的指针来完成。如何实现插入功能?

        struct node **toKeep = (*root)->child;
        (*root)->children+=1;
        (*root)->child =malloc(sizeof(struct node*)*
        (*root)->child = toKeep;
        size_t i; 
        for (i= 0; i < (*root)->children; i++)
        {
            if ((*root)->child[i] == NULL)
            {
                (*root)->child[i] = newNode(type, id);
                printf("%d \n", (*root)->child[i]->id);
                break;
            }
        }

我试图这样做来保留现有节点,但是我无法添加两个以上的节点?是什么原因引起的问题或有更好的书写方法?

c pointers tree
1个回答
0
投票

这是我的主要评论开头。

由于我无法理解您的代码片段的意图,因此我根据之前完成的trie示例重构了代码:

#include <stdlib.h>

typedef struct node node_t;
struct node {
    char *type;

    node_t *parent;
    node_t **child;
    int children;

    int id;
};

// naryfind -- find matching child node based on id
node_t *
naryfind(node_t *par,int id)
{
    size_t cldidx;
    node_t *cld;
    node_t *match;

    match = NULL;

    for (cldidx = 0;  cldidx < par->children;  ++cldidx) {
        cld = par->child[cldidx];

        // skip empty slot
        // NOTE: this will probably never happen based on naryattach
        if (cld == NULL)
            continue;

        if (cld->id == id) {
            match = cld;
            break;
        }
    }

    return match;
}

// narynew -- get new node
node_t *
narynew(int id)
{
    node_t *node;

    node = calloc(1,sizeof(node_t));
    node->id = id;

    return node;
}

// naryattach -- attach new child node
node_t *
naryattach(node_t *par,int id)
{
    size_t cldidx;
    node_t *cld;

    // increase size of array
    cldidx = par->children++;
    par->child = realloc(par->child,sizeof(node_t *) * par->children);

    // allocate new node
    cld = narynew(id);

    // cross-link parent and child
    cld->parent = par;
    par->child[cldidx] = cld;

    return cld;
}

// naryfindx -- find matching child node (create new node if none found)
node_t *
naryfindx(node_t *par,int id)
{
    node_t *cld;

    // find existing node
    cld = naryfind(par,id);

    // create new node if it doesn't already exist
    if (cld == NULL)
        cld = naryattach(par,id);

    return cld;
}
© www.soinside.com 2019 - 2024. All rights reserved.