How to write C functions that modify head pointer of a Linked List?
Last Updated :
10 Jan, 2023
Consider simple representation (without any dummy node) of Linked List. Functions that operate on such Linked lists can be divided into two categories:
1) Functions that do not modify the head pointer: Examples of such functions include, printing a linked list, updating data members of nodes like adding given a value to all nodes, or some other operation that access/update data of nodesĀ
It is generally easy to decide the prototype of functions of this category. We can always pass the head pointer as an argument and traverse/update the list. For example, the following function that adds x to data members of all nodes.
C
void addXtoList(struct Node *node, int x)
{
while(node != NULL)
{
node->data = node->data + x;
node = node->next;
}
}
2) Functions that modify the head pointer:
Examples include, inserting a node at the beginning (head pointer is always modified in this function), inserting a node at the end (head pointer is modified only when the first node is being inserted), deleting a given node (head pointer is modified when the deleted node is the first node). There may be different ways to update the head pointer in these functions. Let us discuss these ways using the following simple problem:
"Given a linked list, write a function deleteFirst() that deletes the first node of a given linked list. For example, if the list is 1->2->3->4, then it should be modified to 2->3->4"
The algorithm to solve the problem is a simple 3 step process: (a) Store the head pointer (b) change the head pointer to point to the next node (c) delete the previous head node.Ā
Following are different ways to update the head pointer in deleteFirst() so that the list is updated everywhere.
2.1) Make head pointer global: We can make the head pointer global so that it can be accessed and updated in our function. Following is C code that uses a global head pointer.
C
// global head pointer
struct Node *head = NULL;
// function to delete first node: uses approach 2.1
// See http://ideone.com/ClfQB for complete program and output
void deleteFirst()
{
if(head != NULL)
{
// store the old value of head pointer
struct Node *temp = head;
// Change head pointer to point to next node
head = head->next;
// delete memory allocated for the previous head node
free(temp);
}
}
See this for a complete running program that uses the above function.
This is not a recommended way as it has many problems like the following:Ā
a) head is globally accessible, so it can be modified anywhere in your project and may lead to unpredictable results.Ā
b) If there are multiple linked lists, then multiple global head pointers with different names are needed.
See this to know all reasons why should we avoid global variables in our projects.Ā
2.2) Return head pointer: We can write deletefirst() in such a way that it returns the modified head pointer. Whoever is using this function, has to use the returned value to update the head node.Ā
C
// function to delete first node: uses approach 2.2
// See http://ideone.com/P5oLe for complete program and output
struct Node *deleteFirst(struct Node *head)
{
if(head != NULL)
{
// store the old value of head pointer
struct Node *temp = head;
// Change head pointer to point to next node
head = head->next;
// delete memory allocated for the previous head node
free(temp);
}
return head;
}
See this for complete program and output.Ā
This approach is much better than the previous 1. There is only one issue with this, if the user misses assigning the returned value to the head, then things become messy. C/C++ compilers allow calling a function without assigning the returned value.Ā
C
head = deleteFirst(head); // proper use of deleteFirst()
deleteFirst(head); // improper use of deleteFirst(), allowed by compiler
2.3) Use Double Pointer: This approach follows the simple C rule: if you want to modify the local variable of one function inside another function, pass a pointer to that variable. So we can pass the pointer to the head pointer to modify the head pointer in our deletefirst() function.Ā
C
// function to delete first node: uses approach 2.3
// See http://ideone.com/9GwTb for complete program and output
void deleteFirst(struct Node **head_ref)
{
if(*head_ref != NULL)
{
// store the old value of pointer to head pointer
struct Node *temp = *head_ref;
// Change head pointer to point to next node
*head_ref = (*head_ref)->next;
// delete memory allocated for the previous head node
free(temp);
}
}
See this for complete program and output.Ā
This approach seems to be the best among all three as there are fewer chances of having problems.
Similar Reads
How to create a pointer to another pointer in a linked list?
In this article we cover how to create a pointer to another pointer in a linked list, it can be singly, doubly, or circularly. What is Linked List: A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked
7 min read
Find intersection point of two Linked Lists without finding the length
There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y shaped list. Write a program to get the point where both the linked lists merge. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -
7 min read
Move all zeros to the front of the linked list
Given a linked list. the task is to move all 0's to the front of the linked list. The order of all other elements except 0 should be the same after rearrangement. Examples: Input : 0 1 0 1 2 0 5 0 4 0 Output :0 0 0 0 0 1 1 2 5 4 Input :1 1 2 3 0 0 0 Output :0 0 0 1 1 2 3Recommended PracticeMove all
11 min read
Print reverse of a Linked List without extra space and modifications
Given a Linked List, display the linked list in reverse without using recursion, stack or modifications to given list. Examples: Input: 1->2->3->4->5->NULLOutput: 5 4 3 2 1 Input: 10->5->15->20->24->NULLOutput: 24 20 15 5 10 Below are different solutions that are now al
7 min read
Write a function to delete a Linked List
Given a linked list, the task is to delete the linked list completely.Examples:Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULLOutput: NULLExplanation: Linked List is Deleted.Input: head: 1 -> 12 -> 1 -> 4 -> 1 -> NULLOutput: NULLExplanation: Linked List is Deleted.Table of C
9 min read
An interesting method to print reverse of a linked list
We are given a linked list, we need to print the linked list in reverse order.Examples: Input : list : 5-> 15-> 20-> 25 Output : Reversed Linked list : 25-> 20-> 15-> 5Input : list : 85-> 15-> 4-> 20 Output : Reversed Linked list : 20-> 4-> 15-> 85Input : list : 8
7 min read
Find kth node from Middle towards Head of a Linked List
Given a Linked List and a number K. The task is to print the value of the K-th node from the middle towards the beginning of the List. If no such element exists, then print "-1". Note: The position of the middle node is: (n/2)+1, where n is the total number of nodes in the list. Examples: Input : Li
14 min read
Delete a Node in a Singly Linked List with Only a Pointer
Given only a pointer to a node to be deleted in a singly linked list. The task is to delete that node from the list. Note: The given pointer does not point to the last node of the linked list.Examples:Input: LinkedList: 1->2->3->4->5, delete_ptr = 2Output: LinkedList: 1->3->4->5
6 min read
Move the Kth element to the Front of a Doubly Linked List
Given a doubly linked list and an integer K, you need to move the Kth element to the front of the list while maintaining the order of the other elements. Examples: Input: DLL: 2 <-> 6 <-> 3 <-> 8 <-> 11 <-> 23 <-> 7 -> NULL, K = 4Output: 8 <-> 2 <->
11 min read
Point arbit pointer to greatest value right side node in a linked list
Given singly linked list with every node having an additional âarbitraryâ pointer that currently points to NULL. We need to make the âarbitraryâ pointer to the greatest value node in a linked list on its right side. A Simple Solution is to traverse all nodes one by one. For every node, find the node
15+ min read