Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a heterogeneous link list in c or c++

A link list that can hold float,integer,character,etc data and algorithm should be well and not very complex

I thought of creating a structure with void pointer that will point to subsequent nodes. but problem is that i cannot use templates with structure.

coming down to c, i have to test each character entered by user to test whether it is integer , float or character or not.then we can proceed further

please suggest an efficient algorithm/code

like image 538
pravs Avatar asked Nov 30 '22 07:11

pravs


1 Answers

If you want to do this yourself you'll basically want to create an array or linked list of elements that encode both the data and the type of data. You could use a struct that includes a type indicator and a union of the various types that you want to handle, and the create an array or linked list of that struct:

typedef struct {
    int type_indicator;
    union {
        float f;
        int i;
        double d;
        void *p;
        char c;
    }
} generic_item;

generic_item generic_array[10];

I'll leave it to you to come up with an appropriate enumeration for the type indicator and to add a function pointer for your algorithm. If you want a linked list instead of an array, you'll obviously also need to add a generic_item *next pointer.

I haven't looked into the boost options that other answers link to, but I'd probably look there first before trying to roll my own solution.

like image 64
Caleb Avatar answered Dec 05 '22 08:12

Caleb