【问题标题】:Using single versus double pointers in Linked lists implemented in C在用 C 实现的链表中使用单指针和双指针
【发布时间】:2012-04-20 01:29:36
【问题描述】:

我正在编写此代码以在链表末尾添加元素:

struct node{
    int info;
    struct node* link;
};

void append ( struct node **q, int num )  
{

struct node *temp, *r ;

if ( *q == NULL )       // if the list is empty, create first node
{
    temp = (struct node*) malloc ( sizeof ( struct node ) ) ;
    temp -> info = num ;
    temp -> link = NULL ;
    *q = temp ;        
}
else{
    temp = *q ;         

    /* go to last node */
    while ( temp -> link != NULL )
        temp = temp -> link ;

    /* add node at the end */
    r = (struct node *)malloc ( sizeof ( struct node ) ) ;
    r -> info = num ;
    r -> link = NULL ;
    temp -> link = r ;
}
}

我这样调用 append 函数: append(&list, 10); 其中list 是指向链表的指针

此代码有效,但如果我在附加函数中使用 single pointer(使用 *q 而不是 **q)并相应地进行更改(如下所示以及当我调用它时),它不起作用。下面的代码有什么问题?:

void append ( struct node *q, int num )  
{

struct node *temp, *r ;

if ( q == NULL )       // if the list is empty, create first node
{
    temp = (struct node*) malloc ( sizeof ( struct node ) ) ;
    temp -> info = num ;
    temp -> link = NULL ;
    q = temp ;        
}
else{
    temp = q ;         

    /* go to last node */
    while ( temp -> link != NULL )
        temp = temp -> link ;

    /* add node at the end */
    r = (struct node *)malloc ( sizeof ( struct node ) ) ;
    r -> info = num ;
    r -> link = NULL ;
    temp -> link = r ;
}
}

【问题讨论】:

  • 因为 C 和 C++ 密切相关,我假设有 C++ 知识的人可以在这里帮助我。
  • 顺便说一句,这是将元素附加到列表的一种不好的方法,因为运行时间会随着元素的数量线性增加。传统的做法是维护一个指向列表两端的指针,这样可以在恒定时间内完成追加。

标签: c pointers linked-list double-pointer


【解决方案1】:

因为在第二个示例中,q 是调用者传入的指针的副本。调用者的原始指针永远不会被修改。

【讨论】:

  • 但是list 是指向节点的指针。因此,它存储了一个地址。所以,当我调用append(list, 10); 时,我传递的是地址,所以,这不应该改变原来的链表吗?
  • @Jatin:不适用于标有“如果列表为空,则创建第一个节点”的代码部分。
  • 所以,假设我在列表中至少有 1 个元素,那么第二个代码就可以了,对吧?
  • 和@Oli,您能否详细说明您的最后评论?
  • @Jatin:if 部分修改了q 的值,但这不会反映在调用者传入的值中(因为它是一个副本)。但是,else 部分没有这样做,所以这部分可能工作正常。
【解决方案2】:

在你的第一个 sn-p 中(这是正确的),你做的太多了。

void append ( struct node **q, int num )  
{

struct node *new ;

    /* go to last node */
    for ( ; *q; q = &(*q)->link ) {;}

    /* add node at the end */
    new = malloc ( sizeof *new );
    if (!new) { barf_now(); return; }

    new->info = num ;
    new->link = NULL ;
    *q = new; ;
    }
}

基本思路是:你要追加到列表的尾部;你需要:

  • 找到第一个 NULL 指针
  • 将其值设置为新指针的值

“空列表”的情况并不特殊,它只是意味着你可以在零步中找到 NULL 指针。以这种方式编码没有特殊情况,也不需要if (...) ... else ... 构造。

【讨论】:

    猜你喜欢
    • 2013-10-29
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    相关资源
    最近更新 更多