0

In linked list Which is better programming practing using double pointers or just declaring head pointer globally

//Here head double pointer is passed as argument

Void insertatend(node **head, int item)
  {
    node *ptr, *loc;
    ptr=(node*)malloc(sizeof(node));
    ptr->info=item;
    ptr->next=NULL;
    if(*head==NULL)
        *head=ptr;
    else
    {
        loc=*head;
        while (loc->next!=NULL)
            {
            loc=loc->next;
            loc->next=ptr;
            }
     }

  }

or this

//Here I have declared head pointer as global

void insert(int x)
  {
   node *ptr,*ptr1;
   ptr=(node*)malloc(sizeof(node));
   ptr->info=x;
   if(head==NULL)
   {
       ptr->next=head;
       head=ptr;
   }
   else
   {
      ptr1=head;   
      while(ptr1->next!=NULL)
      {
          ptr1=ptr1->next;
      }
          ptr1->next=ptr;   
          ptr->next=NULL;
     }
  }
LEO NARDO
  • 17
  • 6

2 Answers2

0

I'd say neither:

void insertatend(node *head, int item)
{
node *ptr, *loc;
ptr=(node*)malloc(sizeof(node));
ptr->info=item;
ptr->next=NULL;
if(head==NULL)
    head=ptr;
else
{
    loc=head;
    while (loc->next!=NULL)
        {
        loc=loc->next;
        loc->next=ptr;
        }
 }

}

I don't know why you would want to change the address to the head pointer inside your function so there's no reason to pass it in as a pointer.

In general, good programming practices will always discourage global variables as you can see in these examples:
Are global variables bad?
Why are global variables evil?
When is it ok to use a global variable in C?

Community
  • 1
  • 1
Matt Ko
  • 969
  • 7
  • 14
0

The double pointer version can be simplified:

Void insertatend(node **head, int item)
{
    node *ptr;
    ptr=(node*)malloc(sizeof(node));
    ptr->info=item;
    ptr->next=NULL;
    while(*head!=NULL)
        head = &((*head)->next);
    *head = ptr;
}
rcgldr
  • 27,407
  • 3
  • 36
  • 61