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

c, data-structures

Solution

Use union to create the datatype

union u_tag{
    char ch;
    int d;
    double dl;
};

struct node {
    char type;
    union u_tag u;
    struct node *next;
};

Use struct node to create linked list. type decides what is the datatype of the data.

Harsha T, Bangalore

Problem

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 elements? If it's possible can you please explain with an example?

Original source

Related problems