
Introduction
There are many such operations where we need to modify the head pointer of a linked list to solve linked list-related problems. But there are also some cases where we can come up with a solution without modifying the head pointer of the linked list. So, we got two types of functions. One is where we don’t need to modify the head pointer of the linked list, and another one is where we will modify the linked list’s head pointer.
Here, we will be only focusing on the functions that modify the head pointer of the linked list.
There are mainly three approaches to how we use a function to modify the head pointer. Before discussing these approaches, let’s see the cases where we need to modify the head pointer.
Also see, Data Structures and Rabin Karp Algorithm.
Cases where modification of head pointer required
If we are inserting or deleting a node from the front of a linked list, in that case, we need to modify the head pointer to point to the new head of the linked list.
Approaches
We will now see the three different approaches on insertion operation where we need to modify the head pointer.
Definition of node structure
typedef structure node{
int data;
structure node* next;
} node;
Method 1
Declaring head as a global variable
We can declare the head pointer of the linked list as global so that it can be accessed from the function where we will modify the head pointer.
void insert_front(int new_val)
{
node* new_node=(node*)malloc(sizeof(node));
new_node->data=new_val;
new_node->next=head;
head=new_node;
}
But there will be issues to maintaining head pointers if we are dealing with multiple linked lists.
Method 2
In this approach, we take the head node pointer as a parameter and return the updated head pointer from the function.
But there is one issue if the programmer forgets to assign the return value to the head pointer where it is called, then we will lose the actual head.
node* insert_front(node* head,int new_val)
{
node* new_node=(node*)malloc(sizeof(node));
new_node->data=new_val;
new_node->next=head;
head=new_node;
return node;
}
Method 3
In this approach, we will modify the head pointer inside the function. So, we need to use a double-pointer in the function as an argument. We will pass the address of the head pointer when the function will be
void insert_front(node** head,int new_val)
{
node* new_node=(node*)malloc(sizeof(node));
new_node->data=new_val;
new_node->next=*head;
*head=new_node;
}