How is generic list manipulation function written?
Asked Answered
E

2

7

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.

Elwandaelwee answered 18/12, 2012 at 5:49 Comment(2)
C is not a very good language for generic programming unfortunatelyTearjerker
This BOOK may help you lot, also a codeFleury
L
2

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);
Legislate answered 18/12, 2012 at 5:59 Comment(0)
T
1

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.

Towpath answered 18/12, 2012 at 5:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.