Computer Science Canada

[TYS] Generic C Linked List Node

Author:  wtd [ Sun Nov 26, 2006 4:25 pm ]
Post subject:  [TYS] Generic C Linked List Node

It's relatively simple to define a linked list node. It's somewhat more challenging to define one which is generic. But not impossibly so. One simply uses a template.

How can the same effect be achieved in C?

What are the caveats to your solution?

Author:  md [ Sun Nov 26, 2006 7:29 pm ]
Post subject: 

void pointers, and it requires casts to get access to members of the list. There is also no way of guaranteeing that every item in the linked list is the same type (this could actually be useful, depending on the situation).

Author:  Andy [ Mon Nov 27, 2006 6:03 pm ]
Post subject: 

what md said, but use a byte to specify the type of the item

Author:  Null [ Tue Nov 28, 2006 8:33 pm ]
Post subject: 

The obvious solution would be:

c:

typedef struct node {
    void *data;
    struct node *next;
} lnode;


But a helpful contributor and compiler writer at another forum came up with something resembling the following code ( I can't say I fully understand the reasoning behind it :p ).

c:


typedef struct node {
    void *_data;
    struct node *_next;

    void *(*data)( void *obj );
    void *(*next)( void *obj );
    void *(*set)( void *obj, void *data);
} lnode;
   
static void *get_data( void *obj ) {
    return ((lnode *)obj)->_data;
}

static void *move_next( void *obj ) {
    return ((lnode *)obj)->_next;
}

static void *set_data( void *obj, void *data ) {
    lnode *node = obj;
    void *old_data = node->_data;
   
    node->_data = data;
    return old_data;
}

static lnode *new_node( void *data, lnode *init_next ) {
    lnode *nn = malloc( sizeof( *nn ) ) ;

   if ( nn == NULL )
       return 0;
   
   nn->_data = data;
   nn->_next = init_next;
   nn->get = get_data;
   nn->next = move_next;
   nn->set = set_data;

   return nn;
}



: