VOOZH about

URL: https://www.geeksforgeeks.org/c/generic-linked-list-in-c-2/

⇱ Generic Linked List in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generic Linked List in C

Last Updated : 23 Jul, 2025

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


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.

Comment
Article Tags: