0

我正在用C设计一个基本的 XML 解析器,并试图找出一种添加节点(子节点和父节点)的方法。所以我现在的想法是有一个数据类型,节点,它看起来像这样

struct node{
    char* name;
    char* value;
    struct node* parent; // if is a child set this to the parent node
    //how to make a list of child nodes
    int numChildren;
    struct node* nextParent;// allow me to iterate through top level parent level nodes
};

因此,如果一个节点是父节点,它将其父指针设置为 NULL。我知道如何将节点添加到我的链表,但我不知道如何将子节点添加到“节点列表”。所以关于我将如何做到这一点的任何想法

4

2 回答 2

2

One common way to create a tree structure is the following:

struct node {
    //additional values...

    struct node *parent; //optional
    struct node *firstChild;
    struct node *nextSibling;
};

Essentially, each node contains a linked list of its children. The first child is theNode->firstChild, the second child is theNode->firstChild->nextSibling, and so on, until nextSibling==NULL for the last child.

Leaf nodes will have firstChild==NULL, and the root node has parent==NULL.

Adding a child to a node will then be done in the same manner as adding a node to a linked list. For example, to add a child in front of the other children:

allocate newNode and initialize its fields.
newNode->parent = parentNode;
newNode->nextSibling = parentNode->firstChild;
parentNode->firstChild = newNode;
于 2012-12-16T15:22:23.730 回答
0
#define MAXCHILD N
struct node{
    char* name;
    char* value;
    struct node* parent; 
    //int numChildren; if fixed number of children for each node then use macro
    struct node* nextParent[MAXCHILD];
};

或者,

尝试使用malloc()和 makenextParent作为struct node** nextParent指针的指针。根据每个节点的子节点数进行分配。像下面这样。

struct node *treenode;
treenode = malloc(sizeof(*treenode));
treenode -> numChildren = 2; // It must be initialized with value otherwise may
// take any garbage value.
treenode -> nextParent = malloc((treenode -> numChildren) * sizeof(struct node*));

但是numChildren应该初始化

于 2012-12-16T15:18:26.477 回答