Generic Linked List

Learn to implement a generic linked list.

Introduction

Linked lists are one of the best examples of why void pointers are useful.

Recall that our previous implementation of linked lists assumes that the values are integers.

typedef struct SList
{
    int value;
    struct SList* next;
} TList;

However, we may want a linked list of float values or even strings. What would be the solution? Defining multiple structures like TListInteger, TListFloat, and TListString isn’t ideal. We’d have to implement the list functions three times, once for each structure. They would be almost identical, with the only exception being the list’s type or perhaps how they handle the value field.

Generic linked lists

The solution is to change the value field from a value to a pointer. Then, we can turn this pointer into a void* by making it accept any data type.

typedef struct SGenericList
{
    void* value;
    struct SGenericList* next;
} TGenericList;
...