by saw 2 ways initiate node?
node c={6, null}; node b={3, &c}; node a={1, &b}; node *root = &a;
node * new_node = (node*)malloc(sizeof(node)); new_node->data = 10; new_node->next = &m;
which better? , right?
another question how can free memory?
for 1, not need free mem right?
for 2, next pointer, free(root->next)
, root->data=null
, right way delete node?
both correct. first 1 relies on instantiating objects on stack , assigning them node *
, later 1 instantiating objects on heap (using malloc
).
free
can used freeing memory allocated malloc.
you right in first case - don't need free mem.
in second case - linked list - create wrapper on free in pass node **
, traverse through linked list until null node, save next node , free
current one. , optionally can set argument null
.