在C中实现的链表中使用单指针和双指针

时间:2012-04-06 12:14:05

标签: c pointers linked-list double-pointer

我正在编写此代码,用于在链接列表的末尾添加元素:

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是指向链接列表的指针

此代码有效,但如果我在追加函数中使用单指针(使用* 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 ;
}
}

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

在你的第一个片段(这是正确的)中,你做得太多了。

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 ...构造。