How is the general list manipulation function written?

I am new to programming, please say goodbye to me, and it is difficult for me to find the answer to my question. I can not get around complex codes. Can someone please explain to me with a simple encoding how the generic list manipulation function written which accepts elements of any kind? Thanks in advance.

+7
source share
2 answers

It looks like you need a heterogeneous list. Some pointers below:

Make a data item from the node list as a general structure that contains an indicator for the data type and data.

  /** This should be your data node **/ struct nodedata { int datatype; void *data; }; /** This should be your list node **/ struct listnode { struct nodedata *data; struct listnode *next; }; 

Using the structure above, you can store various types of data. Use function pointers for comparison functions or call different functions depending on the type of data.

+1
source

This is usually done using void pointers:

 typedef struct node { struct node *next; void *data; } node; node *insert(node *list, void *data) { } node *delete(node *list, node *to_delete) { } 

such manipulation functions are independent of the actual data type; therefore, they can be implemented as a whole. For example, you might have a data type structure for the data field above:

 typedef struct data { int type; void *data; } data; /* .... */ data d; d.type = INT; d.data = malloc(sizeof(int)); node n = {NULL, (void*)&data); 
+1
source

All Articles