Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is generic list manipulation function written?

I am a beginner in programming, please go easy on me and I am finding difficult to get the answer for my question. I can't get my head around the complex codes. Can some one please explain me with simple coding of how is generic list manipulation function written which accepts elements of any kind? Thanks in advance.

like image 482
Korhan Avatar asked Dec 18 '12 05:12

Korhan


2 Answers

This is normally 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 do not depend on the actual type of data so they can be implemented generically. For example you can have a data type struct 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);
like image 52
perreal Avatar answered Oct 29 '22 13:10

perreal


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

Make the data element of the list node as a generic structure, which contains an indicator for 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 above structure, you can store different types of data. Use function pointers for comparison functions or invoke different functions depending upon the data type.

like image 43
Jay Avatar answered Oct 29 '22 13:10

Jay