What is a generic list manipulation function in C? (I saw this when I was going through some materials.)
What is the difference between this function and a function
The Linux kernel has an interesting implementation of a generic linked list in C on its linux/list.h header. It is a doubly-linked list with a head node, used like this:
struct mystruct {
...
/* Contains the next and prev pointers */
struct list_head mylist;
...
/* A single struct can be in several lists */
struct list_head another_list;
...
};
struct list_head mylist_head;
struct list_head another_list_head;
Some interesting things in this small example:
struct list_head, not to the target structure (on the example above, they point to &(foo->mylist) for the first list and &(foo->another_list) for the second list).All the list manipulation functions take pointers to struct list_head (and most do not care at all whether it is the separate head node or one of the embedded nodes). To get from the struct list_head to the target struct, you use the list_entry macro (which is the same as the containter_of macro from the linux/kernel.h header), which expands into a simple pointer subtraction.
Since it is a doubly-linked list with a head node, you can in O(1):