Is there a way to write a single function ( addnode ) for different structures? I’ve this scenario:
typedef struct linkedlist_a *ptr_a;
typedef struct linkedlist_a
{
/* content */
ptr_a next;
} listA;
typedef struct linkedlist_b *ptr_b;
typedef struct linkedlist_b
{
/* content */
ptr_b next;
} listB;
listA *listA_addnode( listA *head, listA *node )
{
listA *temp = head;
if( temp == NULL )
{
temp = node;
}
else if( temp -> next == NULL )
{
temp -> next = node;
}
else
{
while( temp -> next ) temp = temp -> next;
temp -> next = node;
}
return head;
}
listB *listB_addnode( listB *head, listB *node )
{
listB *temp = head;
if( temp == NULL )
{
temp = node;
}
else if( temp -> next == NULL )
{
temp -> next = node;
}
else
{
while( temp -> next ) temp = temp -> next;
temp -> next = node;
}
return head;
}
If there’s two structuress is ok for me write two function but in case I’ve more than 2, how can I do?
Instead of having different
structs that represent a linked list a possible solution would be to have single linked liststructthat hasvoid*member for data. This would allow a singleadd_node()function with a slightly different signature.For example:
There is a danger with this approach, namely the correct interpretation the
datamember. However, with care this approach would meet your requirements.Example use (error checking omitted):
See online demo http://ideone.com/iZO8h.