首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我不能合并2个单向链表

我不能合并2个单向链表
EN

Stack Overflow用户
提问于 2017-10-15 04:51:18
回答 1查看 31关注 0票数 0

我为单向链表的组合2工作。

这是我的节点。

代码语言:javascript
运行
复制
  struct node
{
    int x;
    node *next;
};

这就是合并器。

代码语言:javascript
运行
复制
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;
    }
}

这是主要的函数。

代码语言:javascript
运行
复制
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。

EN

回答 1

Stack Overflow用户

发布于 2017-10-15 05:20:07

在这个循环之后

代码语言:javascript
运行
复制
while(go1!=NULL) go1=go1->next;

指针go1等于NULL,前一节点的数据成员next也等于NULL。如果您要更改指针go1,前一个节点的数据成员next将不会更改,因为它们是占用不同内存区的不同对象。

此外,通常第一个列表可以是空的,因此最初参数go1可以等于NULL,并且更改此参数不会更改原始列表,因为该函数处理原始列表的值的副本。

也是第二个内存分配

代码语言:javascript
运行
复制
    go1=(node*)malloc(sizeof(node));
    go1->x=go2->x;
    go1=(node*)malloc(sizeof(node));

没有任何意义。它会覆盖以前的go1值。因此,存在内存泄漏。

该函数可以按以下方式编写

代码语言:javascript
运行
复制
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;
    }
}

并且该函数可以像这样调用

代码语言:javascript
运行
复制
combine( &head, &head2);

当然,没有必要将第二个参数声明为具有struct node **类型。将其声明为struct node *就足够了。然而,在这种情况下,参数将具有不同的类型,这可能会使函数的用户感到困惑。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46749212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档