lodkkx
lodkkx

Reputation: 1173

How to add a list of structures to an existing structure

I am designing a basic XML parser in C and am trying to figure out a way to add nodes (both child and parents). So my idea as of now is to have one datatype,node, which looks like this

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

So if a node is a parent it will have its Parent pointer set to NULL. I know how to add nodes to my linked list, but I don't get how to add child nodes to a "node list". So any ideas on how I would do that

Upvotes: 0

Views: 159

Answers (2)

Omkant
Omkant

Reputation: 9204

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

Or,

try using malloc() and make nextParent as struct node** nextParent pointer to pointer.Allocate according to number of each node's children. Like this below.

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*));

But numChildren should be initialized

Upvotes: 0

interjay
interjay

Reputation: 110118

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;

Upvotes: 2

Related Questions