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