red_coder's blog

By red_coder, 9 years ago,

below is the function for adding some number to the end of the linked list.......

int add_at_end(struct node **q,int num)
{
struct node *temp;
if(*q==NULL)
{
temp= malloc(sizeof(struct node));
temp->data=num;
*q=temp;
}
else
{
temp=*q;
{
}
r=malloc(sizeof(struct node));
r->data=num;
}
return 0;
}


now my question is what is the need of using double pointer for 'q' , why cant we do the same task using single pointer as below....

int add_at_end(struct node *q,int num)
{
struct node *temp;
if(q==NULL)
{
temp= malloc(sizeof(struct node));
temp->data=num;
q=temp;
}
else
{
temp=q;
{
}
r=malloc(sizeof(struct node));
r->data=num;
}
return 0;
}


• -2

 » 9 years ago, # |   +13 "q=temp" modifies just local variable(defined as parameter of this function), and remains argument unchanged. So actual list will not be changed if q == NULL.While "*q=temp" allow to modify argument itself.But as for me it is a good practice always provide non NULL value to such kind of functions.
•  » » 9 years ago, # ^ |   0 i totally agree with your point but one question, suppose we already know that list is not empty , now if we use single pointer can it work? if yes, then please explain why?
•  » » » 9 years ago, # ^ |   0 Yes it can.When we call a function we provide it a pointer to a struct node (suppose it's name is p). And this pointer is copied to variable q. So now q and p both point to the same structure. So we can modify this structure using both p and q (for example p->data=1; equal to q->data=1). So we can modify it from inside of our function. But if we try to assign different value to q directly, not to some field of structure (q = temp; in your code), original pointer p, which we were going to modify, calling this function will not be affected.It works like next code: node *p = new node(1, 2); node *q = p; q = new node(3, 4);I believe it is clear, that in this case p will not be affected. If it is not — try to debug through it.But if you use a pointer to a pointer as in original code, instead of value of p (which is actually address of node) you have pointer to p, so you can modify it through this pointer
 » 11 months ago, # |   -6 Do we need a linked list in competition programming?
 » 5 weeks ago, # | ← Rev. 2 →   -16 Learn in this tutorial the basic understanding of a linked list, and implementation and analyze how to reverse a linked list in C++.How to reverse a linked list in c++