#include <stdio.h>
struct jsw_node {
void *data;
struct jsw_node *next;
};
struct jsw_list {
struct jsw_node *head;
int has_dummy_head;
size_t size;
};
/*
Create a new node with the given data and links
Returns a pointer to the new node, or NULL on error
*/
struct jsw_node *new_node(void *data, struct jsw_node *next) {
struct jsw_node *rv = malloc(sizeof *rv);
if (rv != NULL) {
rv->data = data;
rv->next = next;
}
return rv;
}
/*
Create a new list with an optional dummy head
Returns a pointer to the new list, or NULL on error
*/
struct jsw_list *new_list(int has_dummy_head)
{
struct jsw_list *rv = malloc(sizeof *rv);
if (rv != NULL)
{
rv->head = has_dummy_head ? new_node(NULL, NULL) : NULL;
rv->has_dummy_head = has_dummy_head;
rv->size = 0;
if (has_dummy_head && rv->head == NULL)
{
/* Release the list if a dummy couldn't be allocated */
free(rv);
rv = NULL;
}
}
return rv;
}
/*
Destroy a single given node, assuming it has been unlinked
Optionally destroy the data contained in the node
Returns the next node specified by the link
*/
struct jsw_node *destroy_node(struct jsw_node *node, void (destroy_data)(void*))
{
struct jsw_node *rv = NULL;
if (node != NULL)
{
/*
Save a reference to the next node
because we're about to destroy this one
*/
rv = node->next;
if (destroy_data != NULL)
{
destroy_data(node->data);
}
free(node);
}
return rv;
}
/*
Destroy all nodes in a given list
Optionally destroy all data in each node
*/
void destroy_list(struct jsw_list *list, void (destroy_data)(void*))
{
while (list->head != NULL)
{
list->head = destroy_node(list->head, destroy_data);
}
}
int main(void) {
printf("Hello World!\n");
return 0;
}