Generic list manipulation function in C?

后端 未结 7 736
独厮守ぢ
独厮守ぢ 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:49

    As mentioned above, I tried using MACROS approach to create the list manipulation functions. Its easy to create the INSERT operation routine but difficult to create Delete and traverse operations. Following it the list structure and the INSERT routine signature:

    #define LIST_DEFINE(type) \
        struct list_node_##type \
        { \
            type *data; \`
            struct list_node_##type *next; \
       };
    
    LIST_INSERT(&ListHead,&Data, DataType);
    

    Where:
    ListHead - Head of the linked list
    Data - The Data for which a new node will be created and data is inserted in the node DataType - Is the data-type of the data passed

    FYI, I am allocating memory in the function and copying all the data passed in the newly created node and them append the node in linked list.

    Now, when a LIST_DELETE routine is created, the node needs to be deleted will be identified using a unique identifier within the data. That identifier is also passed in the MACRO routine as key that will be replaced in the MACRO expansion. The routine signature could be:

    LIST_DELETE(&ListHead, DataType, myvar->data->str, char*);
    

    Where:
    ListHead - Head of the linked list
    DataType - Is the data-type of the data
    myvar->data->str - Unique key
    char* - Key type

    Now, when the key is expanded, that same key cannot be used for comparison as if we write

    if((keytype)ListHead->data->key == (keytype)key)
    

    It expands to

    ListHead->data->myvar->data->str == myvar->data->str
    

    And here there is no variable like: ListHead->data->myvar->data->str

    So, this approach cannot work to write delete routines and as the traversal and search routines also use unique key, same problem will be faced in them as well.

    And, on an unrelated note, how to determine the matching logic for unique key, as the unique key could be anything.

提交回复
热议问题