![]() |
VOOZH | about |
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.
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.
struct Node {
void *data;
struct Node *next;
};
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)
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.