#linked list free
30 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
Sending my current code in a sec
typedef struct _list {
element* first;
int count;
} list;
typedef struct _element {
uint32_t year;
uint64_t isbn;
char author[MAX_STR];
char title[MAX_STR];
struct _element *next;
} element;
element* insert_at_begin(element* first, element* new_elem) {
new_elem -> next = first;
new_elem;
}
element *construct_element(char* title, char* author, uint32_t year, uint64_t isbn) {
element *new_elem = malloc(sizeof(new_elem));
strncpy(new_elem -> title, title, MAX_STR);
new_elem -> title = title;
strncpy(new_elem -> author, author, MAX_STR);
new_elem -> author = author;
new_elem -> year = year;
new_elem -> isbn = isbn;
new_elem -> next = NULL;
}
void free_list(list* BuecherListe) {
element *current_elem = BuecherListe -> first;
}
I was thinking of creating a current_element, which is going to be set to the first element of the list, and then basically just loop through the whole list, while freeing
Is this way of thinking going in the right direction?
yea, i think that's right, although you'll probably want to free the list starting from the end of it
a linked list structurally is like:
{item, ptr}
| (a)
v
{item, ptr}
| (b)
v
{item, ptr}
if you free (a) first which would free the second {item, ptr}, you won't be able to access (b)
oh I get it
so you'd want to free (b) first, then (a), then the first one
but then I need to create a new variable/pointer first right
Or store the pointer to (b) before you free (a)
which is going to point to my last element
yea i was about to say that, raccoon is right
you could also change the pointer of the first to point to the pointer that the one you're freeing is pointing to
that's prolly a cheaper operation too
so like creating a temporary pointer for my next element?
and while im looping, always making that temporary pointer point to my next element
as long as it is not NULL
or something like
while (head->next != NULL) {
// store head.next to prepare to free it
element *next = head->next;
// move head.next.next to head.next, so that pointer is not lost when head.next is freed
head->next = head->next->next;
// finally free what head->next used to point to
free(next);
}
yea exactly like that
thanks!
i believe this should work ? unless i'm being dumb lol
@dusky swift Has your question been resolved? If so, type !solved :)