我为单向链表的组合2工作。
这是我的节点。
struct node
{
int x;
node *next;
};
这就是合并器。
void combine(struct node *go1,struct node *go2)
{
while(go1!=NULL) go1=go1->next;
while(go2!=NULL)
{
go1=(node*)malloc(sizeof(node));
go1->x=go2->x;
go1=(node*)malloc(sizeof(node));
go1=go1->next;
go2=go2->next;
}
}
这是主要的函数。
main()
{
struct node *head;
head = (node*)malloc(sizeof(node));
head -> x = 5;
head -> next = (node*)malloc(sizeof(node));
head -> next -> x = 10;
head -> next -> next = (node*)malloc(sizeof(node));
head -> next -> next -> x = 23;
head -> next -> next -> next = NULL;
struct node *head2;
head2 = (node*)malloc(sizeof(node));
head2 -> x = 5;
head2 -> next = (node*)malloc(sizeof(node));
head2 -> next -> x = 13;
head2 -> next -> next = (node*)malloc(sizeof(node));
head2 -> next -> next -> x = 31;
head2 -> next -> next -> next = NULL;
print(head);
combine(head,head2);
print(head);
execute(head);
}
打印功能是自定义打印列表功能。由我做的简单,执行是免费的()的列表。打印头部,打印只有5,10,23和5,10,23。不包括头2的x值。我想附加头2的x的tp head1。
发布于 2017-10-15 05:20:07
在这个循环之后
while(go1!=NULL) go1=go1->next;
指针go1
等于NULL
,前一节点的数据成员next
也等于NULL
。如果您要更改指针go1
,前一个节点的数据成员next
将不会更改,因为它们是占用不同内存区的不同对象。
此外,通常第一个列表可以是空的,因此最初参数go1
可以等于NULL,并且更改此参数不会更改原始列表,因为该函数处理原始列表的值的副本。
也是第二个内存分配
go1=(node*)malloc(sizeof(node));
go1->x=go2->x;
go1=(node*)malloc(sizeof(node));
没有任何意义。它会覆盖以前的go1
值。因此,存在内存泄漏。
该函数可以按以下方式编写
void combine( struct node **go1, struct node **go2 )
{
while ( *go1 != NULL ) go1 = &( *go1 )->next;
for ( ; *go2 != NULL; go1 = &( *go1 )->next, go2 = &( *go2 )->next )
{
*go1 = ( node* )malloc( sizeof( node ) );
( *go1 )->x = ( *go2 )->x;
( *go1 )->next = NULL;
}
}
并且该函数可以像这样调用
combine( &head, &head2);
当然,没有必要将第二个参数声明为具有struct node **
类型。将其声明为struct node *
就足够了。然而,在这种情况下,参数将具有不同的类型,这可能会使函数的用户感到困惑。
https://stackoverflow.com/questions/46749212
复制相似问题