我正在编写此代码以在链表末尾添加元素:
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 ;
}
}