Home > Net >  How to insert nodes into list by looping?
How to insert nodes into list by looping?

Time:08-22

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

Output:

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

It is my main function in where i call the store function.

int main(int ac, char **av)
{
    Actions action;
    Stack *a;
    Stack *b;
    t_important *data;
    
    if(ac < 2)
        return (-1);
    data = malloc(sizeof(*data));
    stack_nums_counter(av, data);
    collect(av, data);
    __check__collection(data);
    __collecting_ints(data);
    action = init();
    a = NULL;
    b = NULL;
    store(&a, data);
    __sort_a__(&a, &b, data, action);
    return (0);
}

CodePudding user response:

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

If you instead want to insert the important data first in the linked list, you skip the first while loop to find the last next member:

void store(Stack **a, t_important *data) {
    Stack *old_first = *a;
    
    // insert values
    for(int i = 0; i < data->length;   i)
    {
        *a = malloc(sizeof **a);
        (*a)->n = data->collection_of_ints[i];
        a = &(*a)->next;
    }
    
    // link the last inserted node to the old first node
    *a = old_first;
}

CodePudding user response:

You always have uninitialized last node of the stack

    tmp->next = malloc(sizeof(Stack));
    tmp = tmp->next;

So when the stack is outputted then the program invokes undefined behavior.

Also it seems within the caller instead of declaring a pointer of the type Stack * you declared an object of the type Stack and are passing a pointer to it. It is a bad approach.

Nevertheless using your approach the function can be defined the following way

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

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