我有这个结构:
struct node
{
int data;
struct node *next;
};
所以下面的strcut有一个int数据,我希望函数接受CopyFunction,它实际上是一个接受void *并返回void *的函数的指针,我希望我的函数在连接到的第一个节点中获取数据的副本复制f第二个数据,现在我希望数据不仅仅是int我想在任何数据上使用这个函数所以我使用CopyFunction指向一个函数的指针,因为我所说的接受void * ...我怎么能用这在函数下面...例如,如果我想将结构更改为:
struct node
{
Element data;
struct node *next;
};
typedef void* Element;
typedef Element (*copy_function) (Element);
struct node * concatLists( struct node *head1, struct node *head2, int cmp( struct node *),copy_function CopyFunction)
{
struct node *head = NULL;
struct node **current = &head;
for ( ; head1 != NULL; head1 = head1->next )
{
if ( cmp( head1 ) )
{
*current = malloc( sizeof( struct node ) );
( *current )->data = CopyFunction(head1->data);
( *current )->next = NULL;
current = &( *current )->next;
}
}
for ( ; head2 != NULL; head2 = head2->next )
{
if ( cmp( head2 ) )
{
*current = malloc( sizeof( struct node ) );
( *current )->data = CopyFunction(head2->data);
( *current )->next = NULL;
current = &( *current )->next;
}
}
然后,如果我有一个int结构,我可以使用此函数与int的复制函数,如下所示:
static void* copyInt(void* num){
int* newInt=malloc(sizeof(*newInt));
*newInt=*(int*)num;
return newInt;
}
另外我认为如果我改变并且不使用总是struct node *我会想要更好:typedef struct node_t * Node;
1 回答
提供所有"methods"(
cmp
和CopyFunction
)作为参数变得非常快 . 为什么不创建List
"object",它不仅包含指向头部和尾部的指针,而且还包含"methods"以对列表进行泛化 .cmp
可能是一个比较函数(这意味着它应该采用两个参数),这意味着您可能正在尝试合并排序列表 . 好吧,这里的代码使用通用列表实现来做到这一点 . (我想我也可以制作malloc
和free
也可插拔 . )测试: