Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert nodes into list by looping?

How to Implement in right way to store values into linked list? In this example the last element will be "0" . Is there a possible to write the content of while loop that allows me don’t create the last node which will be "0" after allocating in while loop?

void store(Stack *a, t_important *data)
{
    int i;
    Stack *tmp;

    tmp = a;
    i = 0;
    while(i < data->length)
    {
        tmp->n = data->collection_of_ints[i];
        tmp->next = malloc(sizeof(Stack));
        tmp = tmp->next;
        i++;
    }
}

Input:

2->6->0->1->3->5->4

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output:

2->6->0->1->3->5->4->0

>Solution :

I would make store take a Stack** instead:

void store(Stack **a, t_important *data) {
    // find last `next`
    while(*a) a = &(*a)->next;

    // insert values
    for(int i = 0; i < data->length; ++i)
    {
        *a = malloc(sizeof **a);
        (*a)->n = data->collection_of_ints[i];
        a = &(*a)->next;
    }
    *a = NULL; // terminate the linked list
}

and then call it like so

Stack *my_stack = NULL;
store(&my_stack, &some_t_important_instance);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading