red_coder's blog

By red_coder, 13 years ago, In English

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;
    temp->link=NULL;
    *q=temp;
  }
  else
    {
      temp=*q;
      while(temp->link!=NULL)
	{
	  temp=temp->link;
	}
      r=malloc(sizeof(struct node));
      r->data=num;
      r->link=NULL;
      temp->link=r;
    }
  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;
    temp->link=NULL;
    q=temp;
  }
  else
    {
      temp=q;
      while(temp->link!=NULL)
	{
	  temp=temp->link;
	}
      r=malloc(sizeof(struct node));
      r->data=num;
      r->link=NULL;
      temp->link=r;
    }
  return 0;
}
  • Vote: I like it
  • -2
  • Vote: I do not like it

| Write comment?
»
13 years ago, # |
  Vote: I like it +13 Vote: I do not like it

"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.

  • »
    »
    13 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    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?

    • »
      »
      »
      13 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      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

»
4 years ago, # |
  Vote: I like it -6 Vote: I do not like it

Do we need a linked list in competition programming?