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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read