在C中实现的链接列表中使用单指针和双指针 [英] Using single versus double pointers in Linked lists implemented in C
问题描述
我正在编写这段代码,以便在链表的末尾添加元素:
I was writing this code for adding element at the end of linked list:
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
是指向链表的指针
and I call append function like this:
append(&list, 10);
where list
is the pointer to the linked list
此代码有效,但是如果我在附加函数中使用单指针(使用* q代替** q)并进行相应的更改(如下所述,也称为调用")不起作用.下面的代码有什么问题?:
This code works, but if I use single pointer in append function(using *q instead of **q) and make changes accordingly (as done below and also when I call it), it doesn't work. What is wrong with the code below?:
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 ;
}
}
推荐答案
因为在第二个示例中,q
是调用者传递的指针的副本.调用者的原始指针永远不会被修改.
Because in the second example, q
is a copy of the pointer passed in by the caller. The caller's original pointer never gets modified.
这篇关于在C中实现的链接列表中使用单指针和双指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!