This C library provides a set of functions to work with singly linked lists of integers. It includes basic operations like insertion, deletion, and traversal, as well as advanced utilities such as insertion sorting the list.
- Add or remove elements at the head, tail, or specific positions.
- Check for element existence and retrieve list properties.
- Reverse the list or reverse subgroups of the list.
- Memory management with proper freeing of resources.
To use this library, include intlist.h in your project and link with intlist.c. For example:
#include"intlist.h"The library defines the following types:
node_t: Represents a single node in the linked list.list_t: A double pointer to the head node, used to represent the list.
#include"list.h"// Advanced usage for insertion sortintcomparator(constinta, constintb)
{
// Sorts elements in ascending orderreturna-b;
}
intmain() {
node_t*head=NULL;
list_tmy_list=&head;
// Add elementslist_push(my_list, 10);
list_append(my_list, 20);
list_insert_sorted(my_list, 15, comparator);
// Free resourceslist_free(my_list);
return0;
}Get Head:
// Returns the first elementnode_t*head_node=list_head(my_list);
Get Tail:
// Returns the last elementnode_t*tail_node=list_tail(my_list);
Get Next Element:
// Returns the element that follows 10node_t*next_node=list_item_next(my_list, 10);
Access by Index:
node_t*node=list_item_index(my_list, 1); if (node) printf("Value at index 1: %d\n", node->value);
Check for Existence:
// Returns 1 if 20 exists, otherwise 0intexists=list_contains(my_list, 20);
Get Length:
// Returns the number of elementssize_tlen=list_length(my_list);
Push to Head:
// Adds 10 to the start of the listlist_push(my_list, 10);
Append to Tail:
// Adds 20 to the end of the listlist_append(my_list, 20);
Insert After a Value:
// Inserts 15 after the first occurrence of 10list_insert(my_list, 10, 15);
Insert at Index:
// Inserts 15 after the first occurrence of 10list_insert_index(my_list, 1, 25);
Pop Head:
node_t*removed=list_pop_head(my_list);
Pop Tail:
node_t*removed=list_pop_tail(my_list);
Remove by Value:
// Removes the first occurrence of 15list_remove(my_list, 15);
Remove All Instances of a Value:
list_remove_all(my_list, 10);
Remove by Index:
node_t*removed=list_remove_index(my_list, 2);
Reverse Entire List:
list_reverse(my_list);
Reverse Groups of Elements:
// Reverses the list in groups of 3list_reverse_group(my_list, 3);
You can insert items in a sorted manner using a custom comparator function, as described in the first example:
list_insert_sorted(my_list, 30, comparator);Always call list_free to free the memory of the list when it's no longer needed:
list_free(my_list);