【发布时间】: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