Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
Memory efficient doubly linked list
Next article icon

Generic Linked List in C

Last Updated : 27 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A generic linked list is a type of linked list that allows the storage of different types of data in a single linked list structure, providing more versatility and reusability in various applications. Unlike C++ and Java, C doesn’t directly support generics. However, we can write generic code using a few tricks.

In this article, we will learn how to create a generic linked list in C so that the same linked list code can be worked with different data types.

How to Create a Generic Linked List in C?

In C, we can use a void pointer and a function pointer to implement the generic functionality. The great thing about void pointers is that they can be used to point to any data type. Also, the size of all types of pointers is always the same, so we can always allocate a linked list node. A function pointer along with the size of the data_type is needed to process actual content stored at the address pointed by the void pointer.

Generic Linked List Node Structure

struct Node {
void *data;
struct Node *next;
};

C Program to Implement Generic Linked List

C
// C program for implementing a generic linked list #include <stdio.h> #include <stdlib.h> #include <string.h>  struct Node {        // Any data type can be stored in this node     void  *data;     struct Node *next; };  // Function to insert data at head. This functions requires // the size of the data type as extra argument struct Node* insertAtHead(struct Node* head, void *data,                    size_t data_size) {        // Allocate memory for node     struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));      newNode->data = malloc(data_size);     newNode->next = head;      // Copy contents of data to newly allocated memory.     memcpy(newNode->data, data, data_size);  	return newNode; }  // Function that access and prints the linked list. This function needs // to know how many bytes of memory is to be read to print the data // So a function pointer is required for printing different data type void printList(struct Node *head, void (*fptr)(void *)) {     while (head != NULL) {         (*fptr)(head->data);         head = head->next;     } }  // Helper function to print an integer void printInt(void *n) {    printf(" %d", *(int *)n); }  // Helper function to print a float void printFloat(void *f) {    printf(" %f", *(float *)f); }  int main() {      // Create an int linked list   	// 10 -> 20 -> 30 -> 40   	struct Node *head = NULL;  	unsigned i_size = sizeof(int);  	int i_arr[4] = {40, 30, 20, 10};   	head = insertAtHead(head, i_arr, i_size);   	head = insertAtHead(head, i_arr + 1, i_size);   	head = insertAtHead(head, i_arr + 2, i_size);   	head = insertAtHead(head, i_arr + 3, i_size);           	// Printing the Integer list     printf("Created integer linked list is \n");     printList(head, printInt);          // Create an float linked list   	// 10.1 -> 20.2 -> 30.3 -> 40.4   	head = NULL;  	unsigned f_size = sizeof(float);  	float f_arr[4] = {40.4, 30.3, 20.2, 10.1};   	head = insertAtHead(head, f_arr, f_size);   	head = insertAtHead(head, f_arr + 1, f_size);   	head = insertAtHead(head, f_arr + 2, f_size);   	head = insertAtHead(head, f_arr + 3, f_size);           	// Printing the Float list     printf("\n\nCreated float linked list is \n");     printList(head, printFloat);            return 0; } 

Output
Created integer linked list is   10 20 30 40  Created float linked list is   10.100000 20.200001 30.299999 40.400002

Time Complexity: O(N), here N is number of nodes in linked list.
Auxiliary Space: O(N)

Advantages of Generic Linked List

  • This linked list handles different data types without changing the implementation.
  • The same linked list structure and functions can be reused across various applications.
  • Only one set of functions needs to be maintained for different data types.

Limitations of Generic Linked List

  • The use of void pointers can lead to type safety issues, requiring careful handling.
  • The implementation can be more complex than specific data type-linked lists due to generic handling.

Conclusion

A generic linked list in C provides a powerful tool for managing collections of various data types. By using void pointers and function pointers, the same linked list implementation can handle different types of data, enhancing flexibility and code reuse. However, it requires careful handling of memory and data types to avoid common pitfalls associated with generic programming in C.



Next Article
Memory efficient doubly linked list
author
kartik
Improve
Article Tags :
  • C Language
  • C Programs
  • C-DSA
  • C-Pointers

Similar Reads

  • Advanced Data Structures
    Advanced Data Structures refer to complex and specialized arrangements of data that enable efficient storage, retrieval, and manipulation of information in computer science and programming. These structures go beyond basic data types like arrays and lists, offering sophisticated ways to organize and
    3 min read
  • Generic Linked List in C
    A generic linked list is a type of linked list that allows the storage of different types of data in a single linked list structure, providing more versatility and reusability in various applications. Unlike C++ and Java, C doesn't directly support generics. However, we can write generic code using
    5 min read
  • Memory efficient doubly linked list
    We need to implement a doubly linked list with the use of a single pointer in each node. For that we are given a stream of data of size n for the linked list, your task is to make the function insert() and getList(). The insert() function pushes (or inserts at the beginning) the given data in the li
    9 min read
  • XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
    In this post, we're going to talk about how XOR linked lists are used to reduce the memory requirements of doubly-linked lists. We know that each node in a doubly-linked list has two pointer fields which contain the addresses of the previous and next node. On the other hand, each node of the XOR lin
    15+ min read
  • XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
    In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert
    10 min read
  • Skip List - Efficient Search, Insert and Delete in Linked List
    A skip list is a data structure that allows for efficient search, insertion and deletion of elements in a sorted list. It is a probabilistic data structure, meaning that its average time complexity is determined through a probabilistic analysis. In a skip list, elements are organized in layers, with
    6 min read
  • Self Organizing List | Set 1 (Introduction)
    The worst case search time for a sorted linked list is O(n). With a Balanced Binary Search Tree, we can skip almost half of the nodes after one comparison with root. For a sorted array, we have random access and we can apply Binary Search on arrays. One idea to make search faster for Linked Lists is
    3 min read
  • Unrolled Linked List | Set 1 (Introduction)
    Like array and linked list, the unrolled Linked List is also a linear data structure and is a variant of a linked list. Why do we need unrolled linked list? One of the biggest advantages of linked lists over arrays is that inserting an element at any location takes only O(1). However, the catch here
    10 min read
  • Splay Tree

    • Searching in Splay Tree
      Splay Tree- Splay tree is a binary search tree. In a splay tree, M consecutive operations can be performed in O (M log N) time. A single operation may require O(N) time but average time to perform M operations will need O (M Log N) time. When a node is accessed, it is moved to the top through a set
      15+ min read

    • Insertion in Splay Tree
      It is recommended to refer following post as prerequisite of this post.Splay Tree | Set 1 (Search)As discussed in the previous post, Splay tree is a self-balancing data structure where the last accessed key is always at root. The insert operation is similar to Binary Search Tree insert with addition
      15+ min read

    Trie

    • Trie Data Structure Tutorial
      The trie data structure, also known as a prefix tree, is a tree-like data structure used for efficient retrieval of key-value pairs. It is commonly used for implementing dictionaries and autocomplete features, making it a fundamental component in many search algorithms. In this article, we will expl
      15+ min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences