Better programming practice in linked list

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; } }

-------------Problems Reply------------

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?
Python: Why are global variables evil?
When is it ok to use a global variable in C?

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;
}

Category:c# Views:2 Time:2017-09-13

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.179 (s). 10 q(s)