Is it possible to have a linked list of different data types?

后端 未结 11 2063
独厮守ぢ
独厮守ぢ 2020-12-13 22:22

This is just another interview question.

Can we have a linked list of different data types, i.e. each element in a linked list can have different structure or union

11条回答
  •  有刺的猬
    2020-12-13 23:04

    Well in a linked list you don't HAVE to link like for like structs together. As long as they have the appropriate forward and/or backwards pointers you are fine. For example:

    struct BaseLink
    {
       BaseLink* pNext;
       BaseLink* pPrev;
       int       typeId;
    };
    
    struct StringLink
    {
        BaseLink baseLink;
        char* pString;
    };
    
    struct IntLink
    {
        BaseLink baseLink;
        int   nInt;
    };
    

    This way you'd have a linked list that goes from BaseLink to BaseLink. The extra data is not a problem. You want to see it as a StringLink? Then cast the BaseLink to a StringLink.

    Just remember that you need some form of typeid in there so you know what to cast it to when you arrive at it.

提交回复
热议问题