Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [TYS] Generic C Linked List Node
Index -> Programming, C++ -> C++ Tutorials
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: 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?
Sponsor
Sponsor
Sponsor
sponsor
md




PostPosted: Sun Nov 26, 2006 7:29 pm   Post subject: (No 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).
Andy




PostPosted: Mon Nov 27, 2006 6:03 pm   Post subject: (No subject)

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




PostPosted: Tue Nov 28, 2006 8:33 pm   Post subject: (No 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;
}

Display posts from previous:   
   Index -> Programming, C++ -> C++ Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 4 Posts ]
Jump to:   


Style:  
Search: