Generic list manipulation function in C?

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

    I have been trying something different. This is another perspective how to board the problem

    If we have the follow structure:

    typedef struct token {
        int id;
        char *name;
        struct token *next;
    } Token;
    

    and we need to create a function that returns the tail of a linked list, but the function should be generic for any linked list, so:

    void* tail(void* list, void* (*f)(void *)) {
        void *head = list;
    
        while(f(head) != NULL) {
            head = f(head);
        }
    
        return head;
    }
    

    Now will be necessary create a function responsible to do the bridge between the our custom struct to a generic usability in the tail function. In that way, we have:

    void* nextToken(void *a) {
        Token *t = (Token *) t;
        return (void *) (a->next);
    }
    

    Finally we can simply use:

    Token *listTokens;
    (...)
    Token *lastToken = tail(listTokens, nextToken);
    

提交回复
热议问题