Generic list manipulation function in C?

后端 未结 7 763
独厮守ぢ
独厮守ぢ 2020-12-16 05:53

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

7条回答
  •  情话喂你
    2020-12-16 06:35

    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:

    • The list node is embedded within the target struct, needing no data pointer.
    • The list node does not have to come at the beginning of the target struct.
    • A single struct can be in several linked lists at the same time.
    • The next and prev pointers within the list point to the 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):

    • Check if the list is empty, or if a node is not on any list.
    • Get the node after or before any other node (if the node is the head, you get the first or last element of the list).
    • Insert a node after or before any other node (if the node is the head, you insert at the beginning or end of the list).
    • Remove a node from the list (you need only the pointer to the node itself to do this).
    • Several other operations.

提交回复
热议问题