
155 views
Generic Linked list in C
You can create a generic linked list by using pointers to void
or by leveraging C’s union
data type to store different types of data in each node of the list. Here’s an example of how you can create a simple generic linked list:
C
#include <stdio.h>
#include <stdlib.h>
// Define a structure for a generic linked list node
typedef struct Node {
void* data; // Pointer to the data (generic)
struct Node* next; // Pointer to the next node
} Node;
// Function to create a new node with generic data
Node* createNode(void* data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
perror("Memory allocation failed");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the beginning of the list
void insertAtBeginning(Node** head, void* data) {
Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
// Function to print the elements of the list (assuming int data)
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", *(int*)(current->data));
current = current->next;
}
printf("\n");
}
// Function to free the memory used by the list
void freeList(Node* head) {
Node* current = head;
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp->data); // Free the data pointer
free(temp); // Free the node
}
}
int main() {
Node* head = NULL;
// Insert elements of different types (int and double) into the list
int num1 = 42;
double num2 = 3.14;
insertAtBeginning(&head, &num1);
insertAtBeginning(&head, &num2);
// Print the list
printf("List elements: ");
printList(head);
// Free the memory used by the list
freeList(head);
return 0;
}
In this example, we use a struct Node
to create a generic linked list node. The data
field is a pointer to void
, allowing us to store data of any type. The insertAtBeginning
function inserts a new node at the beginning of the list, and the printList
function is used to print the elements (assuming int
data in this case). Finally, the freeList
function is used to free the memory used by the list.
You can modify this code to support other data types or add additional functionality as needed for your specific use case.