0

这里是链表的节点:

struct Node {
char data;
struct Node *next;
int pindex; //this is the first index position in parent[] which is null, next element goes here
int cindex; //this one for child array
char parent[50];
char child[50];
};

这就是我创建每个节点的方式。

struct Node *createNode(struct Node *node, char nodeData) {
if(root == NULL) {
    int i=0;
    node= malloc(sizeof(struct Node));
    node->data = nodeData;
    while(i<50) {
        node->parent[i]= '\0';
        node->child[i]= '\0';
        i++;
    }
    node->pindex=0;
    node->cindex=0;
    node->next= malloc(sizeof(struct Node));
    root=node;
    return node;
}
else if (node->data == 0) {
    int j=0;
    node->data = nodeData;
    while (j<50) {
        node->parent[j]= '\0';
        node->child[j]= '\0';
        j++;
    }
    node->pindex=0;
    node->cindex=0;
    node->next= malloc(sizeof(struct Node));
    return node;
}
else
    return createNode(node->next, nodeData);
}

这是我的代码,我在其中更新特定节点中父数组和子数组的值。

void insert(char a, char b) {
struct Node *pNode, *cNode;
    if (hasNode(root,a))  //check if Node with node->data ='a' exists else create it
        pNode= getNode(root,a);
    else {
        pNode= createNode(root,a);
        //addToFirst(one); No need as we already have list of all elements
    }
    if (hasNode(root, b))
        cNode= getNode(root,b);
    else
        cNode= createNode(root, b);
pNode->child[(pNode->cindex)] = b; //insert a char into child array of parent node 
pNode->cindex++;
cNode->parent[(cNode->pindex)]= a; // insert char into child array of parent node
cNode->pindex++;
}

问题出在以下部分

pNode->child[(pNode->cindex)] = b; //insert a char into child array of parent node 
pNode->cindex++;
cNode->parent[(cNode->pindex)]= a; // insert char into child array of parent node
cNode->pindex++;

当任何元素被插入到 cNode 的 parent[] 中时,它的 child[] 就会从内存中消失。如果我稍后将任何东西插入孩子,它的工作。

以下是我为此链接列表截取的屏幕截图,应该会有所帮助。数据根->下一个节点中缺少子数组

【数据结构截图】

4

0 回答 0