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

Problem Statement

Explain different ways in which the head pointer of a linked list can be modified inside a C function.

Problem Overview

In this article, we are going to look at different ways in which the head of a linked list can be modified. Now, why would we need to modify the head of a linked list?

In a lot of operations, such as insertion and deletion at the beginning, we need to somehow modify the head. Now, the head is of type pointer to node. A pointer passed into a function by value can’t be modified to point to something else, only the data inside it can be changed. So, let’s look at different ways in which we can solve this issue.

Let us take an operation Insertion at the beginning of a linked list, where we need to modify the head of a linked list.

Approach 1

Declaring head as a global variable.

If we declare head as a global variable, it will be accessible inside every function. So, we will be able to modify it as per our needs.

Code Implementation

Node *head = NULL;
void push_front(int new_val){
    Node* new_node = new Node(new_val);
    new_node->next = head;
    
    head = new_node;
}

Approach 2

By returning the head node from the function.

If the head pointer is passed to a function by value, then we can’t change it inside that function. If we return the copy of the head pointer from the function after modifying it and update the original head in the caller function, the head pointer will be modified.

Code Implementation


Node* push_front(Node* head, int new_val){
    Node* new_node = new Node(new_val);
    new_node->next = head;
    
    head = new_node;
    return head;
}

int main(){
    Node *head = NULL;
    head = push_front(head, 2);
}

The head pointer will be updated in the caller function.

Approach 3

By passing the head pointer as a double pointer to the function.

Another way to change the head pointer inside the called function itself is by passing as a double-pointer. In that case, we need to pass the address of the head as an argument to the called function.

Code Implementation


void push_front(Node** head, int new_val){
    Node* new_node = new Node(new_val);
    new_node->next = (*head);
    
    *head = new_node;
}

int main(){
    Node *head = NULL;
    push_front(&head, 2);
}

All the above approaches can be used depending on the usage to modify the head pointer.

In the above article, we went through a basic but very important concept regarding the pointers in C++. Concepts like these are very necessary to understand pointers well. I would highly recommend you to practice some problems on the linked list from Linked List.

Previous post Practice problems for linked list and recursion
Next post Generic Linked List in C

Leave a Reply

Your email address will not be published. Required fields are marked *