|
Quick Navigation Bar structures :: advanced data structures :: make and makefiles [ toc | forums ] |
Note: If the document URL does not begin with http://randu.org/tutorials/c/ then you are viewing a copy. Please direct your browser to the correct location for the most recent version. |
struct llnode {
<type> data;
struct llnode *next;
};
The <type> signifies data of any type. This is typically a
pointer to something, usually another struct. The next line
is the next pointer to another llnode struct. Another more
convenient way using typedef:
typedef struct list_node {
<type> data;
struct list_node *next;
} llnode;
llnode *head = NULL;
Note that even the typedef is specified, the next
pointer within the struct must still have the struct
tag!root node of
the linked list. One method is to create a head pointer and the
other way is to create a dummy node. It's usually easier to
create a head pointer.
void add(llnode **head, <type> data_in) {
llnode *tmp;
if ((tmp = malloc(sizeof(*tmp))) == NULL) {
ERR_MSG(malloc);
(void)exit(EXIT_FAILURE);
}
tmp->data = data_in;
tmp->next = *head;
*head = tmp;
}
/* ... inside some function ... */
llnode *head = NULL;
<type> *some_data;
/* ... initialize some_data ... */
add(&head, some_data);
What's happening here? We created a head pointer, and then
sent the address-of the head pointer into the add
function which is expecting a pointer to a pointer. We send in
the address-of head. Inside add, a tmp pointer is allocated
on the heap. The data pointer on tmp is moved to point to
the data_in. The next pointer is moved to point to the head
pointer (*head). Then the head pointer is moved to point
to tmp. Thus we have added to the beginning of the
list.
void freelist(llnode *head) {
llnode *tmp;
while (head != NULL) {
free(head->data); /* Don't forget to free memory within the list! */
tmp = head->next;
free(head);
head = tmp;
}
}
Now we can rest easy at night because we won't have memory leaks in
our lists!
