добавление информации в child-> child LINKED LIST - PullRequest
0 голосов
/ 02 января 2019

Итак, я пытаюсь создать программу с несколькими дочерними элементами, в которой есть несколько дочерних элементов, например:

root = NULL.

-root->child  (this one contain the first file name)
--root->child->child  (this one contain the information inside the file)
-root->child  (second file name)
--root->child->child  (second file information)

Итак, моя главная проблема - поместить правильную информацию в ребенка.

Поэтому мне интересно, идет ли мой путь с хорошей логикой или мне следует начинать с 0 снова.

это моя структура:

typedef struct      s_lst
{
    char            *content; //path name 
    int             data;     //path number
    struct s_lst    *next;
    struct s_lst    *child;
}                   t_lst;

это мой код:

int main(int ac, char **av)
{
    t_lst *root;
    root = NULL;
    root = new_node(0,0);
    add_child(root, "first-child", 0);
    for (int i = 0; i < 4; i++)
        lst_add(&(root)->child->child, new_node("inside first child child", i));
    add_child(root, "second", 0);
    for (int i = 0; i < 4; i++)
        lst_add(&(root)->child->child, new_node("inside second child child", i));
    ft_print(root);
}

t_lst   *new_node(char *name, int data)
{
    t_lst *new_node;

    if (!(new_node = malloc(sizeof(t_lst))))
        return (0);
    new_node->content = name;
    new_node->data = data;
    new_node->next = NULL;
    new_node->child = NULL;
    return (new_node);
}

t_lst   *add_sibling(t_lst *n, char *name, int data)
{
    if (n == NULL)
        return (NULL);
    while (n->next)
        n = n->next;
    return (n->next = new_node(name, data));
}

t_lst   *add_child(t_lst *n, char *name, int data)
{
    if (n == NULL)
        return (NULL);

    if (n->child)
        return (add_sibling(n->child, name, data));
    else
        return (n->child = new_node(name, data));
}

void    lst_add(t_lst **head, t_lst *new)
{
    t_lst   *tmp;

    if (*head)
    {
        tmp = *head;
        while (tmp->next)
            tmp = tmp->next;
        tmp->next = new;
    }
    else
        *head = new;
}

ft_print:

void    ft_print(t_lst *root)
{
    while (root)
    {
        while (root->child)
        {
            printf("%s\n", root->child->content);
            printf("-----------------------------\n");
            while (root->child->child)
            {
                printf("node->child->child %s\n", root->child->child->content);
                root->child->child = root->child->child->next;
            }
            printf("\n");
            root->child = root->child->next;
        }
        root = root->next;
    }
}

также изображение в качестве примера: вот пример того, что я пытаюсь сделать. Как видите, второй «текст» входит в моего первого ребенка. спасибо за вашу помощь, с трудом изучая связанный список: D!

1 Ответ

0 голосов
/ 02 января 2019

Ваша основная проблема в том, что во втором цикле вы добавляете в тот же (первый) дочерний элемент:

for (int i = 0; i < 4; i++)
    lst_add(&(root)->child->child, new_node("inside second child child", i));
//                        ^~~~~~~
//              should be ->next->child here

Еще лучше было бы воспользоваться возвращаемыми значениями add_child, которые сделают логику намного более ясной:

t_lst *first_child = add_child(root, "first-child", 0);
for (int i = 0; i < 4; i++)
    lst_add(&first_child->child, new_node("inside first child child", i));

t_lst *second_child = add_child(root, "second-child", 0);
for (int i = 0; i < 4; i++)
    lst_add(&second_child->child, new_node("inside second child child", i));

Другая проблема, которую вы еще не обнаружили , заключается в том, что вы изменяете свои списки в функции ft_print:

void ft_print(t_lst *root)
{
    while (root)
    {
        while (root->child)
        {
            ...
            while (root->child->child)
            {
                ...
                root->child->child = root->child->child->next;
                // reassigning and effectively "loosing" child nodes here
            }
            ...
            root->child = root->child->next;
            // and here
        }
        root = root->next;
    }
}

Вы должны использовать локальные переменные для перебора дочерних узлов:

t_lst *current = root->child;
while (current)
{
    ...
    current = current->next;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...