top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to write C functions that modify head pointer of a Linked List?

+2 votes
527 views
How to write C functions that modify head pointer of a Linked List?
posted Apr 9, 2014 by Atul Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

There can be following three approaches -

Preference One: Use Double Pointer

void deleteFirst(struct node **head_ref)
{
    if(*head_ref != NULL)
    {
       struct node *temp = *head_ref;     
       *head_ref = (*head_ref)->next;     
       free(temp);
    }
}

Preference Two: Return head pointer

struct node *deleteFirst(struct node *head)
{
    if(head != NULL)
    {
       struct node *temp = head; 
       head = head->next; 
       free(temp);
    }

    return head;
}

Preference Three: Global Head Pointer (should be avoided)

struct node *head = NULL;

void deleteFirst()
{
    if(head != NULL)
    {
       struct node *temp = head;        
       head = head->next; 
       free(temp);
    }
}
answer Apr 9, 2014 by anonymous
...